Reputation: 19
i need to build up an ArrayList
with Integer
in new Array
s in it. How can I setup this and add items?
private final ArrayList<Integer>[] test;
test = new ArrayList<Integer>();
This won't work.
Thank you!
Upvotes: 0
Views: 1438
Reputation: 41223
An array is an Object
, and you can make lists of any object type - so you can make a List
of arrays without doing anything special:
// Declare it and initialise as an empty list
List<Integer[]> list = new ArrayList<>();
// Add an item -- it's a new array
list.add(new Integer[5]);
// Access an item -- it's an array
Integer[] array = list.get(0);
Integer x = array[0];
I see few reasons to use arrays of Integer
for most situations, however. An array of int
is also an Object
so you can use that just as well.
List<int[]> list = new ArrayList<>();
list.add(new int[5]);
One of the most common reasons for using the object Integer
rather than the primitive int
is that you can't have List
s of primitives. But you can have arrays of primitives, so if you're happy with the lesser expressive power of the array, by all means populate it with primitives.
Ask yourself why you want a List
of arrays rather than a List
of List
s, an array of arrays or an array of List
s, however.
Your question asks for "Arrays inside an ArrayList".
List<Integer[]>
is a list of arrays (because, inside the <>
, is Integer[]
).
List<Integer>[]
is an array of lists -- "ArrayLists inside an array" -- because the []
comes after the List<>
declaration.
You can initialise your array of lists just like any other array, with new Type[length]
:
// Declare it
List<Integer>[] array = new List<Integer>[5];
// Put something into an array element
array[3] = new ArrayList<Integer>();
// Access an element -- it's a List
List<Integer> list = array[3];
Integer x = list.get(0);
Upvotes: 2
Reputation: 897
u can use like this for do this
private ArrayList<Integer>[] test ;
private void test(int n){
test=new ArrayList[n];
for(int i=0;i<n;i++){
test[i]=new ArrayList<Integer>();
test[i].add(100);
test[i].add(10);
test[i].add(10000);
test[i].add(1);
....
}
}
Upvotes: 0
Reputation: 26
Looks like you want to create a 2-dimansional integer array.
I assume you have a special use case in which you need a primitive array ob ArrayList-Objects.
Anyways you can create such a thing like any other primitive array like
ArrayList<Integer>[] test = new ArrayList[2];
and access/set it by index..
test[0] = new ArrayList<Integer>();
You also can fill the array on init...
ArrayList<Integer>[] test = new ArrayList[] {
new ArrayList<Integer>(),
new ArrayList<Integer>(),
new ArrayList<Integer>()
};
Upvotes: 0
Reputation: 14568
If we want Arrays inside List then -
class Test {
private final List<int[]> myList;
public Test() {
myList = new ArrayList<>();
}
public void add(int[] myArray) {
myList.add(myArray);
}
}
You are always allowed to initialize a final variable. The compiler makes sure that you can do it only once.
Upvotes: 0