Reputation: 313
folks, what is the technique of copying elements from array
to Arraylist
?
public DenseBoard(T[][] x, T fillElem){
ArrayList<ArrayList<T>> myBoard = new ArrayList<ArrayList<T>>();
for(int i = 0; i < x.length; i++){
for(int j = 0; j < x[0].length; j++){
myBoard.get(i).add(j); //<<------ getting error!
}
}
}
Upvotes: 2
Views: 881
Reputation: 76434
Inspired from this post.
new ArrayList<Item>(Arrays.asList(array))
creates a new ArrayList
of Item
elements from an input array. For two-dimensionals. In this case, you tried this:
public DenseBoard(T[][] x, T fillElem){
ArrayList<ArrayList<T>> myBoard = new ArrayList<ArrayList<T>>();
for(int i = 0; i < x.length; i++){
for(int j = 0; j < x[0].length; j++){
myBoard.get(i).add(j); //<<------ getting error!
}
}
}
The problem is that the line throwing the error assumes you have an ArrayList
of ArrayList
, but the inner element you try to refer to is not initialized. This should be a fix:
public DenseBoard(T[][] x, T fillElem){
ArrayList<ArrayList<T>> myBoard = new ArrayList<ArrayList<T>>();
for(int i = 0; i < x.length; i++){
myBoard.add(new ArrayList<T>(Arrays.asList(x[i])));
}
//Do something with myBoard
}
Upvotes: 0
Reputation: 8652
You are getting error because your are trying to get()
a value from ArrayList
but not had inserted any value first. To do it your way, here is the correct code :
ArrayList<ArrayList<T>> myBoard = new ArrayList<>();
for(int i = 0; i < x.length; i++){
ArrayList<T> values = new ArrayList<>();
for(int j = 0; j < x[0].length; j++){
values.add(x[i][j]);
}
myBoard.add(values);
}
Just use the following function :
Arrays.asList(T...a)
In your case it will be done as :
ArrayList<T> myBoard = new ArrayList<>();
for(T[] arr : x){
myBoard.add(Arrays.asList(arr));
}
diamond operator <>
to make code more readablefor-each
statement where you couldUpvotes: 1
Reputation: 7573
You'll need to initialize each member of myBoard in the outer loop:
public DenseBoard(T[][] x, T fillElem){
ArrayList<ArrayList<T>> myBoard = new ArrayList<ArrayList<T>>();
for(int i = 0; i < x.length; i++){
myBoard.add(new ArrayList<T>); //Gotta add something to stick stuff in
for(int j = 0; j < x[0].length; j++){
myBoard.get(i).add(j); //<<------ no more error?
}
}
}
Since myBoard is an ArrayList of ArrayLists of Ts, we need to give it somewhere to put the T's. Initially, myBoard looks like this:
[] <-- empty ArrayList
So we give it somewhere to put data for each row, like this
myBoard.add(new ArrayList<T>);
Now it looks like
[ [] ] <--- ArrayList with an empty ArrayList in it, ready to accept T's
We add some T's, and end up with this
[ [T1, T2, T3] ].
And on the next iteration, we'll end up with something like this
[ [T1, T2, T3], [T4, T5, T6] ]
Hope that cleared things up.
Upvotes: 1