Let say I want to create an array of length 5 through the default constructor
public class A <E extends Comparable<? super E>> implements B<E>
{
private E[] myArray;
public A()
{
myArray = (E[]) new Object[5];
}
}
Is this the right way of doing it? I’m confused that whether I have to
state “Comparable” before []. so
private Comparable[] myArray;
The problem with the code you posted is that the erasure of
E[]isComparable[](becauseE‘s upper bound isComparable), so casting an object whose real type isObject[]toComparable[]will fail.You could simply change it to the following and it won’t throw the exception:
However, there is more subtlety here:
myArrayis not really of typeE[]. Inside the class,E[]is erased toComparable[], so it is okay. But you have to make sure never to exposemyArrayto outside of the class. Since it is private, you just have to make sure that no method returns it or something.The benefit of doing it this way, keeping
myArrayof typeE[], over Jatin’s answer of usingComparable[], is that you don’t have to cast every time you get something out of it, so the code is nicer.