1

Trying to create an Object array, but get "cannot create a generic array of Object".

I tried to cast it with (Object[]), but it didn't help.

public class Container<Object> {
 Object start;

  Container(Object start){
     this.start=start;
 }

 LinkedList<Object> save = new LinkedList<>();

 public Object[] toArray() {
    Object[] test = (Object[]) new Object [3]; // cannot create here
    for (int i=0; i<save.size(); i++)
    {
            ...
    }
}
  • 5
    I'm guessing you have a generic parameter named `Object`. Please provide a [mcve]. – shmosel Mar 28 '19 at 19:32
  • 1
    The code you show looks valid and does not produce the error you are talking about. Provide a [mcve]. Else, it is likely that the question will be closed. – Zabuzard Mar 28 '19 at 19:33
  • 2
    And there you have it. Rename the parameter. Your'e hiding `java.lang.Object`. – shmosel Mar 28 '19 at 19:36
  • In your class, there now exist two things with the name `Object`. Your generic parameter and the actual class `java.lang.Object`. Java will assume the generic type, since its from the lower scope. So it thinks you want to create a generic array, which is not possible like that (if that is your question, google it, there are duplicates to it). – Zabuzard Mar 28 '19 at 19:38

0 Answers0