大家都知道,泛型数组是不能直接用new分配空间的,只有先通过以Object数组方式分配空间再强制转化为泛型。
但是当我用了比较复杂的泛型参数时,出现了ClassCastException的异常,代码如下public class Test {
public static void main(String[] args){
Test.<Integer>test();
}
public static <T extends Comparable<T>> void test() {
T[] result = (T[]) new Object[10];
}
}如果<T extends Comparable<T>>改为<T>的话就可以顺利执行,想了半天还是找不出问题,望高手指教,谢谢。
但是当我用了比较复杂的泛型参数时,出现了ClassCastException的异常,代码如下public class Test {
public static void main(String[] args){
Test.<Integer>test();
}
public static <T extends Comparable<T>> void test() {
T[] result = (T[]) new Object[10];
}
}如果<T extends Comparable<T>>改为<T>的话就可以顺利执行,想了半天还是找不出问题,望高手指教,谢谢。
解决方案 »
- 关于equals的问题
- 内部类做监听器的问题<anonymous myframe$1> is not abstract and does not override abstract method actionPerformed
- Java能够实现Xml序列化
- 编译通过,运行异常,大家帮我分析一下
- 出现jdbc问题
- 关于JAVA Object 反序列化的问题,如何将一个格式化的String反序列化成对应的Java object
- SWING组件中,有没有控制光标状态的方法?
- 如何判断一个远程文件是否存在?
- SSL有错,高手指点???
- 各位高手别嫌分少,帮帮忙!!我怎么才能获取主机名,来着有分!
- 问个问题,我准备j2ee方向,我还用学一下swing不了?
- java打包成ISO
public static void main(String[] args) {
Test.<String> test();
} public static <T extends Comparable<T>> void test() {
T[] result = (T[]) new String[10];
result[0] = (T) new String("1");
System.out.println(result[0]);
}
}理由是换成这样就ok
public static void main(String[] args) {
Test.<MyInteger> test();
} public static <T extends Comparable<T>> void test() {
T[] result = (T[]) new MyInteger[10];
result[0] = (T) new MyInteger(1);
System.out.println(((MyInteger) result[0]).getValue());
}
}class MyInteger implements Comparable{
int value;
MyInteger(int value){
this.value = value;
}
public void setValue(int value){
this.value = value;
}
public int getValue(){
return value;
} public int compareTo(Object o) {
// TODO Auto-generated method stub
return 0;
}
}
T[] result = (T[]) new Comparable[10];
}