Reputation: 33
I have 9 ArrayList
s and I'm trying to condense them all down into one at a given point.
at the moment dotGrid
is a matrix of ArrayList
s, searchX
and searchY
simply specify which ArrayList
s to add to neighbours
.
for(int searchX = sector[0] - 1; searchX < sector[0] + 2; searchX++){
for(int searchY = sector[1] - 1; searchY < sector[1] + 2; searchY++){
if(searchX >= 0 && searchX < 16 && searchY >= 0 && searchY < 16){
neighbours.add(dotGrid[searchX][searchY]);
}
}
}
from what I understand neighbours.addAll()
should work, but it isn't.
I really have been searching quite hard, but haven't been able to find a satisfactory answer.
thanks in advance
Upvotes: 0
Views: 4593
Reputation: 120516
In
neighbours.add(dotGrid[searchX][searchY])
dotGrid
is an array. Typically, you can't instantiate an array of a fully qualified generic type:
List<Double>[][] dotGrid = new List<Double>[n][];
will fail with a type error, so I'm going to assume that dotGrid
is partially typed?
List[][] dotGrid;
which means that addAll(dotGrid[searchX][searchY])
will fail because you are trying to add all elements of a List
to a List<Double>
.
Ideally, you wouldn't mix object arrays with generic lists, and instead redefine dotGrid
to be a list of lists of lists:
List<List<List<Double>>> dotGrid;
If that won't work, you can try to @SuppressWarning("unchecked")
to make sure that dotGrid
has a fully qualified type after instantiation, or do something like the following
@SuppressWarning("unchecked")
List<Double> cell = (List<Double>) dotGrid[searchX][searchY];
neighbours.addAll(cell);
Upvotes: 2
Reputation: 36611
The List#add
method expects an element which can be added to the List
. So if your dotGrid
is a 'matrix of ArrayList
s', you try to add an ArrayList
to your List
instead of adding all elements of that List
. You should use the addAll
method instead as you mentioned in your answer, but in your code you use the regular add
method
neighbours.addAll(dotGrid[searchX][searchY]);
The following code works just fine, illustrating the usage of the addAll
method
List<Integer> list = new ArrayList<Integer>( Arrays.asList( 0, 1 ) );
List<Integer> anotherList = new ArrayList<Integer>( );
anotherList.addAll( list );
Upvotes: 0