and*_*dge 2 java generics casting
可能重复:
使用Java创建通用数组
我想将一般的对象数组修剪为只有第一个len元素.这似乎应该工作:
@SuppressWarnings("unchecked")
public static <T> T[] trimArray(T[] data, int len){
T[] result = (T[]) new Object[len];
System.arraycopy(data, 0, result, 0, len);
return result;
}
Run Code Online (Sandbox Code Playgroud)
但是如果我做类似的事情,它会引发ClassCastException
public class Foo{
double f;
public Foo(double f){
this.f = f;
}
}
public static void main(String[] args){
Foo[] A = new Foo[10];
A[0]= new Foo(1);
A[1]= new Foo(2);
A[2]= new Foo(3);
Foo[] B = trimArray(A, 3);
}
Run Code Online (Sandbox Code Playgroud)
fge*_*fge 11
JDK已经内置了这个:
Foo[] B = Arrays.copyOf(A, 3);
Run Code Online (Sandbox Code Playgroud)
Javadoc(自1.6起)
但是请注意,如果源数组长度小于所需长度,它还将扩展数组(用nulls 填充).您可以使用以下方法轻松解决此问题:
Foo[] B = Arrays.copyOf(A, Math.min(3, A.length));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7054 次 |
| 最近记录: |