铸造Arrays.asList引起的异常:java.util.Arrays中的$ ArrayList中不能被强制转换为java.util.ArrayList中 [英] casting Arrays.asList causing exception: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList

查看:312
本文介绍了铸造Arrays.asList引起的异常:java.util.Arrays中的$ ArrayList中不能被强制转换为java.util.ArrayList中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的Java,我试图理解为什么第一个code片段不会引起此异常,但第二个呢。因为一个字符串数组传递到Arrays.asList在这两种情况下,不应同时片段产生一个异常或没有产生异常?

I'm new to Java and am trying to understand why the first code snippet doesn't cause this exception but the second one does. Since a string array is passed into Arrays.asList in both cases, shouldn't both snippets produce an exception or not produce an exception?

Exception in thread "main" java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList

首先片段(导致没有例外):

First snippet (causes no exception):

ArrayList<ArrayList<String>> stuff = new ArrayList<ArrayList<String>>();
String line = "a,b,cdef,g";
String delim = ",";
String[] pieces = line.split(delim);
stuff.add((ArrayList<String>) Arrays.asList(pieces));

第二个片段(原因上面的除外):

Second snippet (causes above exception):

ArrayList<ArrayList<String>> stuff = new ArrayList<ArrayList<String>>();
String[] titles = {"ticker", "grade", "score"};
stuff.add((ArrayList<String>) Arrays.asList(titles));

如果相关的,我使用的JavaSE 1.6在Eclipse赫利俄斯。

If relevant, I'm using JavaSE 1.6 in Eclipse Helios.

推荐答案

对于我来说(使用Java 1.6.0_26),第一个片断给出了同样的异常作为第二个。其原因是,在<一href=\"http://download.oracle.com/javase/1.4.2/docs/api/java/util/Arrays.html#asList%28java.lang.Object%5B%5D%29\"><$c$c>Arrays.asList(..)方法并只返回一个列表,不一定是的ArrayList 。因为你真的不知道什么样的(或实施的)列表该方法的回报,你投以的ArrayList&LT ;弦乐&GT; 是不是安全。其结果是,它可能或可能无法正常工作。从编码风格的角度来看,良好的修复程序,这将是改变你的的东西声明:

For me (using Java 1.6.0_26), the first snippet gives the same exception as the second one. The reason is that the Arrays.asList(..) method does only return a List, not necessarily an ArrayList. Because you don't really know what kind (or implementation of) of List that method returns, your cast to ArrayList<String> is not safe. The result is that it may or may not work as expected. From a coding style perspective, a good fix for this would be to change your stuff declaration to:

List<List<String>> stuff = new ArrayList<List<String>>();

这将允许添加任何散发出来的 Arrays.asList(..)方法。

这篇关于铸造Arrays.asList引起的异常:java.util.Arrays中的$ ArrayList中不能被强制转换为java.util.ArrayList中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆