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.
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.
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.
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".
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.
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
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With