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?
ArrayList can not be used for primitive types, like int, char, etc. We need a wrapper class for such cases.
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.
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.
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)
.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With