List of Arrays in Java

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.

3

3 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

4
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);  
} 
3

List is an interface, not a class. You have to choose what kind of list. In most cases an ArrayList is chosen.

List a = new ArrayList();

You've mentioned that you want to store an int array in it, so you can specify the type that a list contains.

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". This is because arrays are objects, but an "int" is a primitive.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest