The reason you get the exception in a seemingly strange place is because of erasure. Erasure of Key
is Comparable
so the cast here actually never happens at run time:
keys = (Key[]) new Comparable[NMAX];
But as you've observed, a cast does happen when you retrieve the array from outside the object. A Comparable[]
is not a Double[]
so you get the exception. As long as you don't access the array outside the class, the way you're doing it probably won't cause a problem.
The "safer" idiom is to make the array non-generic by making its declaration a Comparable[]
. Then you:
- Ensure that only
Key
can be put in the array. - Make the unchecked cast on a retrieval call.
Something like this:
@SuppressWarnings("rawtypes")
public class General<Key extends Comparable<Key>> {
private Comparable[] keys;
public General(int NMAX) {
keys = new Comparable[NMAX];
}
public void set(int ind, Key k) {
keys[ind] = k;
}
@SuppressWarnings("unchecked")
public Key get(int ind) {
return (Key)keys[ind];
}
}
That's type safe and it's the way the JDK does it.
Another way is to have the client provide the array:
public class General<Key extends Comparable<Key>> {
private Key[] keys;
public General(Key[] keys) {
this.keys = keys;
}
}
You should also consider using a List instead because they do all this stuff for you and are fully generic. You can just do new ArrayList<Key>()
.