尝试将 setInstance.toArray() 转换为 Integer[],没有编译时错误但有 运行 时间错误,为什么?
Trying to cast setInstance.toArray() to Integer[], no compile time error but there is run time error, why?
我正在试验 Java HashSet class 及其 toArray() 方法。下面是我想出的代码。编译器没有显示任何错误,但是当我 运行 代码时, IDE 输出错误消息:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;
at JTOCollection.TheCollectionInterface.main(TheCollectionInterface.java:26)
Java Result: 1
由于我的经验不足,我无法完全理解错误消息背后的完整原因,能否请大神解释一下?
Set<Integer> set1 = new HashSet<>();
set1.add(1);
set1.add(2);
set1.add(3);
set1.add(2);
Integer[] intArray = (Integer[]) set1.toArray();
for(Integer i : intArray){
System.out.println(i);
}
set1.toArray()
是一个 Object[],不能转换为 Integer[]。如果你想要一个 Integer[] 试试这个:
Integer[] intArray = set1.toArray(new Integer[set1.size()]);
因为您使用的是 public Object[] toArray()
而不是 public <T> T[] toArray(T[] a)
。
使用这个:
Integer[] intArray = set1.toArray(new Integer[set1.size()]);
文档:public <T> T[] toArray(T[] a)
Returns an array containing all of the elements in this collection;
the runtime type of the returned array is that of the specified array.
If the collection fits in the specified array, it is returned therein.
Otherwise, a new array is allocated with the runtime type of the
specified array and the size of this collection.
方法set1.toArray() return Object[],你需要将returned数组中的每个对象显式转换为Integer。以下代码适合您。
Set<Integer> set1 = new HashSet<>();
set1.add(1);
set1.add(2);
set1.add(3);
set1.add(2);
Object[] intArray = set1.toArray();
for(Object i : intArray){
System.out.println(i);
}
我正在试验 Java HashSet class 及其 toArray() 方法。下面是我想出的代码。编译器没有显示任何错误,但是当我 运行 代码时, IDE 输出错误消息:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;
at JTOCollection.TheCollectionInterface.main(TheCollectionInterface.java:26)
Java Result: 1
由于我的经验不足,我无法完全理解错误消息背后的完整原因,能否请大神解释一下?
Set<Integer> set1 = new HashSet<>();
set1.add(1);
set1.add(2);
set1.add(3);
set1.add(2);
Integer[] intArray = (Integer[]) set1.toArray();
for(Integer i : intArray){
System.out.println(i);
}
set1.toArray()
是一个 Object[],不能转换为 Integer[]。如果你想要一个 Integer[] 试试这个:
Integer[] intArray = set1.toArray(new Integer[set1.size()]);
因为您使用的是 public Object[] toArray()
而不是 public <T> T[] toArray(T[] a)
。
使用这个:
Integer[] intArray = set1.toArray(new Integer[set1.size()]);
文档:public <T> T[] toArray(T[] a)
Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array. If the collection fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this collection.
方法set1.toArray() return Object[],你需要将returned数组中的每个对象显式转换为Integer。以下代码适合您。
Set<Integer> set1 = new HashSet<>();
set1.add(1);
set1.add(2);
set1.add(3);
set1.add(2);
Object[] intArray = set1.toArray();
for(Object i : intArray){
System.out.println(i);
}