Alan2
Alan2

Reputation: 24602

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?

Upvotes: 26

Views: 94979

Answers (4)

nobeh
nobeh

Reputation: 10049

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).

Upvotes: 47

Nikhil Nanivadekar
Nikhil Nanivadekar

Reputation: 1152

You can use primitive collections available in Eclipse Collections. Eclipse Collections has List, Set, Bag and Map for all primitives. The elements in the primitive collections are maintained as primitives and no boxing takes place.

You can initialize a IntList like this:

MutableIntList intList = IntLists.mutable.empty();

Note: I am a contributor to Eclipse Collections.

Upvotes: 1

wattostudios
wattostudios

Reputation: 8774

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)

Upvotes: 10

Adel Boutros
Adel Boutros

Reputation: 10295

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

Upvotes: 4

Related Questions