0

I have 9 ArrayLists and I'm trying to condense them all down into one at a given point.

at the moment dotGrid is a matrix of ArrayLists, searchX and searchY simply specify which ArrayLists 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

2
  • 3
    "neighbours.addAll() should work, but it isn't." What is not working? Does it give an error? Or yield strange results? Commented Jan 8, 2012 at 12:48
  • A more complete code example would be useful (pastebin), noteably the declarations for dotGrid and neigbours. Also, you're not using neighbours.addAll there. Commented Jan 8, 2012 at 12:51

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

0

The List#add method expects an element which can be added to the List. So if your dotGrid is a 'matrix of ArrayLists', 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 );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.