求JDK1.5 泛型数组拷贝函数

sinall 2008-05-29 02:56:00
注意,是JDK1.5
自己写了一个:

package vec.server.util;

import java.util.ArrayList;

public class ArraysCopyer {

public static <T> T[] copyOf(T[] original,
int newLength) {
if (newLength < 0) {
throw new NegativeArraySizeException();
}

if (original == null) {
throw new NullPointerException();
}

ArrayList<T> target = new ArrayList<T>(newLength);
for (int i = 0; i < newLength; ++i) {
target.add(i, original[i]);
}
for (int i = newLength; i < original.length; ++i) {
target.add(i, null);
}

return (T[])(target.toArray());
}

private ArraysCopyer() { };

}

使用的时候:
AttrToken[] attrs = ArraysCopyer.copyOf(orig, count);

结果异常:
ClassCastException
...全文
88 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
jdlsfl 2008-05-29
  • 打赏
  • 举报
回复
AttrToken[] attrs = ArraysCopyer.copyOf(orig, count);

楼主不能这样使用的
ArraysCopyer.copyOf返回的object[],并不是你想象的AttrToken[]

楼主这样定义使用泛型的意义不大
不要返回数组,定义和返回arraylist<T>会比较有意义
sinall 2008-05-29
  • 打赏
  • 举报
回复
造型异常出在什么位置啦
——AttrToken[] attrs = ArraysCopyer.copyOf(orig, count);

我测试的没问题
——你是JDK1.5吗?
老紫竹 2008-05-29
  • 打赏
  • 举报
回复
我测试的没问题
  public static void main(String[] args) {
String[] list = { "1", "2", "3", "4" };
Object[] os = copyOf(list, 3);
for (Object o : os) {
System.out.println((String)o);
}
}

burningice44 2008-05-29
  • 打赏
  • 举报
回复
造型异常出在什么位置啦

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧