简体   繁体   中英

Java 2D Int Arraylist

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

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

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

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

Try use:

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

您必须创建一个ArrayList<Integer>而不是ArrayList<int>一个类(在您的情况下为Arraylist )可以是CLASS的类型( Integer

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM