Nick Robertson
Nick Robertson

Reputation: 1047

Cannot create a generic array in Java

I try to create a generic array but I'm taking the error of the title.

 ByteConverter<Product> byteconverter = new ByteConverter<Product>();

 //into an inner class I have to declare a final field 
 final ByteConverter<Product>[] byteconverter2 = {byteconverter};

So, I searched at the Stackoverflow for a possible solution. I found something similar here: Cannot create an array of LinkedLists in Java...? , so I canged my code to the following:

 final ByteConverter<Product>[] byteconverter2 = {(ByteConverter<Product>[])byteconverter};

but I still take the same error. I can't understand why..Any help please?

Upvotes: 0

Views: 2102

Answers (2)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

This compiles, though with a warning

    ByteConverter<Product> byteconverter = new ByteConverter<Product>();
    ByteConverter<Product>[] byteconverter2 = new ByteConverter[] { byteconverter };

Read here http://docs.oracle.com/javase/tutorial/java/generics/restrictions.html about restrictions for generics

Upvotes: 1

Ilya
Ilya

Reputation: 29673

final ByteConverter<Product>[] byteconverter2 = 
   new ByteConverter[]
   {
      byteconverter   
   };

this works well

Upvotes: 2

Related Questions