Reputation: 389
I dont quite understand what is the problem with the second declaration.
// Compiles fine
ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>();
// error (Unexpected type, expected -reference ,found :int)
ArrayList<ArrayList<int>> intarray = new ArrayList<ArrayList<int>>();
Upvotes: 0
Views: 1334
Reputation: 27356
The way generics work is simple. The header of List
looks a little like this:
public interface List<T>
Where T
is some Object
. However, int
is not a subclass of Object
. It is a primitive. So how do we get around this? We use Integer
. Integer
is the wrapper class for int
. This allows us to use int
values in a List
, because when we add them, they get auto boxed into Integer
.
Primitive types are actually scheduled for deprecation in Java 10. Taken from Wikipedia:
There is speculation of removing primitive data types, as well as moving towards 64-bit addressable arrays to support large data sets somewhere around 2018.
Just a Note on your Code
In Java, the convention is to have the declaration using the most generic type and the definition using the most specific concrete class. For example:
List myList;
// List is the interface type. This is as generic as we can go realistically.
myList = new ArrayList();
// This is a specific, concrete type.
This means that if you want to use another type of List
, you won't need to change much of your code. You can just swap out the implementation.
Extra Reading
Upvotes: 3
Reputation: 3592
You can only make List of Objects. int is a primitive type.
Try use:
ArrayList<ArrayList<Integer>> intarray = new ArrayList<ArrayList<Integer>>();
Upvotes: 1
Reputation: 13232
ArrayList does not except primitive types as an argument. It only accepts Object types you should use:
ArrayList<ArrayList<Integer>> intArray = new ArrayList<ArrayList<Integer>>();
Upvotes: 0
Reputation: 8662
ArrayList
is an implementation of List<T>
, your problem is that you are trying to create an arraylist of int, its impossible since int
is not an object. using Integer
will solve your problem.
ArrayList<ArrayList<Integer>> intarray = new ArrayList<ArrayList<Integer>>();
Upvotes: 3
Reputation: 4199
You must create an ArrayList<Integer>
not an ArrayList<int>
A class(Arraylist
in your case) can be a type of a CLASS (Integer
)
Upvotes: 0