0

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>>();

5 Answers 5

3

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>>();
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1

You can only make List of Objects. int is a primitive type.

Try use:

ArrayList<ArrayList<Integer>> intarray = new ArrayList<ArrayList<Integer>>();

Comments

0

You must create an ArrayList<Integer> not an ArrayList<int> A class(Arraylist in your case) can be a type of a CLASS (Integer)

1 Comment

Victor - Updated the question( was wrongly formateed)
0

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>>();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.