Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new ArrayList<int>() failing in Java

I have the following code:

List<int> intList = new ArrayList<int>();
for (int index = 0; index < ints.length; index++)
{
    intList.add(ints[index]);
}

It gives me an error...

Syntax error on token "int", Dimensions expected after this token

The error occurs on the line starting with List. Can someone explain why I am getting the error?

like image 660
Alan2 Avatar asked Jun 17 '12 06:06

Alan2


People also ask

Can you use INT in ArrayList Java?

ArrayList can not be used for primitive types, like int, char, etc. We need a wrapper class for such cases.

Can an ArrayList hold ints?

An ArrayList cannot store ints. To place ints in ArrayList, we must convert them to Integers. This can be done in the add() method on ArrayList. Each int must be added individually.

Can you initialize an ArrayList with values in Java?

Java developers use the Arrays. asList() method to initialize an ArrayList. Using asList() allows you to populate an array with a list of default values. This can be more efficient than using multiple add() statements to add a set of default values to an ArrayList.


3 Answers

Generics in Java are not applicable to primitive types as in int. You should probably use wrapper types such as Integer:

List<Integer> ints = ... 

And, to access a List, you need to use ints.get(index).

like image 131
nobeh Avatar answered Oct 04 '22 07:10

nobeh


You can only use an Object type within the <> section, whereas you're trying to use a primitive type. Try this...

List<Integer> intList = new ArrayList<Integer>(); 

You then need to access the values using intList.get(index) and intList.set(index,value) (and also intList.add(value) as you are trying to do)

like image 25
wattostudios Avatar answered Oct 04 '22 07:10

wattostudios


you should use Integer instead of int because lists requires object not primitive types. but u can still add element of type int to your Integer list

like image 35
Adel Boutros Avatar answered Oct 04 '22 07:10

Adel Boutros