0

I created the class Queue with

import java.util.LinkedList;
public class Queue <T>{
        private LinkedList<T> list;

        public Queue() {
            list = new LinkedList<>();
        }

        ...
}

I also created the class Cinema, which has a private field of an array of Queue<String>.

public class Cinema {
    private Queue<String>[] arr;
    
    public Cinema() {
        arr = new Queue<String>[10];
        for (int i = 0; i < 10; i++)
            arr[i] = new Queue<String>();
    }

        ...
}

However, the line arr = new Queue<String>[10]; throws a compilation error, saying Cannot create a generic array of Queue<String>. But as I understand it the array isn't generic, as its generic type is defined to be String.

When I change the line to

arr = new Queue[10];

the code works again, although it still gives me a warning saying Type safety: The expression of type Queue[] needs unchecked conversion to conform to Queue<String>[]. So I don't understand why the original doesn't work.

1
  • 1
    The short answer is that arrays and generics just never mix well. Commented Jan 30, 2023 at 17:11

1 Answer 1

0

But as I understand it the array isn't generic, as its generic type is defined to be String.

Different meanings of the same word. What the compiler means is: There are <> and/or type vars involved anywhere in the array type. Which you can't do.

Arrays are low-level constructs that you don't use except for classes that define new collection concepts. You aren't doing that here. Ditch the array, make a List<Queue<String>> instead.

If you insist on using arrays, you're doing it: arr = new Queue[10]. Yes, this gets a warning. The only thing you can do is live with it, or use @SuppressWarnings. Arrays and generics don't mix very well. Hence, don't - use List<Queue<String>> instead.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.