-1

i am trying to create this:

Queue<Integer>[] my_var;

When I try to allocate it, intellij gives me this:

my_var = new Queue[4];

Is this Correct? And Also Will I have to innitialize all the elements seperatly?

To be clear what i want is an array of queues

Unihedron
  • 10,251
  • 13
  • 53
  • 66

3 Answers3

3

To be clear what i want is an array of queues

Please, don't. It has been said multiple times, that arrays and generics don't mix well. You could create an array of Queue using raw types, but don't. Raw types should be avoided in all cases.

Instead, create an List, like

List<Queue<Integer>> m;

You might want to read How to create a generic array?

Community
  • 1
  • 1
dumbPotato21
  • 5,353
  • 5
  • 19
  • 31
2

You need to change a couple of things:

  • If you are trying to declare Queue of Integer elements then you don't need angular braces ([]) it can just be: Queue<Integer> and not Queue<Integer>[]
  • Queue is an interface in Java and hence, you can't instantiate it with new. You need to use any of the Implementation of Queue, e.g.:

    Queue<Integer> my_var;
    my_var = new LinkedBlockingQueue<>();
    

    And yes, you will have to initialize all the elements separately, or just add the Integers with add method of Queue.

    Here are the Queue implementations, you can select any of these depending on your use case.

Darshan Mehta
  • 27,835
  • 7
  • 53
  • 81
0

It is right,if you want to create a queue of int, try Queue<Integer> var

dawnfly
  • 83
  • 2