This code works correctly and print out number 120. However, if I uncomment the line in the main function.
The code is throwing an exception: Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Comparable; cannot be cast to [Ljava.lang.Double; at General.main
I searched and found several discussion on generics array in java. People acknowledged the treatment of generics array is not very well in java. But I still feel very bad about this code: print out a line in different places will have different consequences, (execution correctly versus throw an exception).
Could someone please comment on this code and advise if there is any simple fix to the exception related to the println code in the main function?
Here is my code :
public class General<Key extends Comparable<Key>> {
public Key[] keys;
@SuppressWarnings("unchecked")
public General(int NMAX) {
keys = (Key[]) new Comparable[NMAX];
System.out.println(keys.length);
}
public static void main(String[] args){
General<Double> g = new General<Double>(120);
// System.out.println(g.keys.length);
}
}
System.out.println(g.keys.length);