当我使用带有比较器的Arrays.sort()和作为集合的列表(之前转换为数组)时,我得到一个类强制转换异常.这是我的代码:
List<SomeClazz> somes = new ArrayList<SomeClazz>();
Comparator<SomeClazz> attrComparator = new AttrComparator();
somes = createSomeObjectes(); // returnes a list of course
// this is line 25 where the exception occours
Arrays.sort((SomeClazz[])somes.toArray(), attrComparator);
Run Code Online (Sandbox Code Playgroud)
例外消息:
Exception in thread "main" java.lang.ClassCastException:
[Ljava.lang.Object; cannot be
cast to [Lpack.SomeClazz; at pack.TestMain.main(TestMain.java:25)
Run Code Online (Sandbox Code Playgroud)
这可能是什么原因?提前thx!
(SomeClazz[])somes.toArray()
Run Code Online (Sandbox Code Playgroud)
应该
somes.toArray(new SomeClazz[somes.size()])
Run Code Online (Sandbox Code Playgroud)
您无法转换Object[]为a SomeClazz[],但这是将集合转储为您选择的数组类型的"已批准"方式.
| 归档时间: |
|
| 查看次数: |
286 次 |
| 最近记录: |