26

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?

wattostudios
  • 8,666
  • 13
  • 43
  • 57
Alan2
  • 23,493
  • 79
  • 256
  • 450

4 Answers4

47

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

Michael Mior
  • 28,107
  • 9
  • 89
  • 113
nobeh
  • 9,784
  • 10
  • 49
  • 66
10

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)

wattostudios
  • 8,666
  • 13
  • 43
  • 57
4

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

Adel Boutros
  • 10,205
  • 7
  • 55
  • 89
1

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.

Nikhil Nanivadekar
  • 1,152
  • 11
  • 10