0

I need to create and use an array of Deques, something like the following

Deque<Point>[] saved = new LinkedList<Point>[12];

This code results in an error because Java doesn't allow you to create generic arrays of Deques. Is there a way to set up the array of Deques so I can access each individual Deque when I need to?

I also tried:

Deque<Point>[] saved;
//....
for(int i = 0;i<12;i++)
{
     saved[i] = new LinkedList<Point>;
}

which returns a NullPointerException. How can I create this array?

2
  • @Jens I'm afraid not, I get the same "Cannot create a generic array of Deque<Point>" Commented Mar 16, 2017 at 13:09
  • 1
    you can do Deque<Point>[] saved = new Deque[12]; .... Commented Mar 16, 2017 at 13:13

2 Answers 2

2

You need to initialize saved to an ArrayList:

// Note that saved has a size defined at construction, 
// which makes this efficient. 
final List<Deque<Point>> saved = new ArrayList<Deque<Point>>(12);
for (int i = 0; i < 12; i++) {
   saved.add(new LinkedList<Point>());
}
Sign up to request clarification or add additional context in comments.

4 Comments

Doesn't work I'm afraid, I get the same complaint about not being able to create a generic array of Deque<Point>
Ah, of course. An ArrayList with a size defined at construction should work well. Updated the answer.
@imulsion There is no array creation in that code. What line of code is giving you that error?
The updated solution worked perfectly. Thanks very much for your help.
1

Why you don't use ArrayDeque?

You can use this :

ArrayDeque arr = new ArrayDeque<Point>(12);

Or this :

LinkedList l = new LinkedList<Point>();
ArrayDeque arr = new ArrayDeque(l);

There are a good tutorial here Java.util.ArrayDeque Class

1 Comment

I was thinking about the same thing. ArrayDeque is a Fast Deque Operations Using an Array.

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.