Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of Arrays in Java

Tags:

java

arrays

list

What is the syntax for making a List of arrays in Java?

I have tried the following:

List<int[]> A = new List<int[]>(); 

and a lot of other things.

I need to be able to reorder the int arrays, but the elements of the int arrays need not to be changed. If this is not possible, why?

Thank you.

like image 612
Chet Avatar asked Nov 30 '11 06:11

Chet


People also ask

Can you have a list of arrays in Java?

The Java lists are not limited to storing primitive data types. We can store objects, arrays, and any other complex data type in a list, and we should note that a list can even store a null element.

Can I have a list of arrays?

It is possible. However, it's not possible to have a list containing multiple types. The hack is to create all Object arrays and store your values, but if you need this kind of hack you should probably rethink about your approach.

How do you represent an ArrayList in Java?

List a = new ArrayList(); List<int[]> a = new ArrayList<int[]>(); While you can have a collection (such as a list) of "int[]", you cannot have a collection of "int".

What is ArrayList types of array?

ArrayList of arrays can be created just like any other objects using ArrayList constructor. In 2D arrays, it might happen that most of the part in the array is empty. For optimizing the space complexity, Arraylist of arrays can be used.


2 Answers

Firstly, you can't do new List(); it is an interface.

To make a list of int Arrays, do something like this :

List<int[]> myList = new ArrayList<int[]>(); 

P.S. As per the comment, package for List is java.util.List and for ArrayList java.util.ArrayList

like image 70
gprathour Avatar answered Oct 14 '22 01:10

gprathour


List<Integer[]> integerList = new ArrayList<Integer[]>(); 

Use the object instead of the primitive, unless this is before Java 1.5 as it handles the autoboxing automatically.

As far as the sorting goes:

Collections.sort(integerList); //Sort the entire List   

and for each array (probably what you want)

for(Integer[] currentArray : integerList)   {       Arrays.sort(currentArray);   }  
like image 39
Woot4Moo Avatar answered Oct 14 '22 02:10

Woot4Moo