异常转化问题: java.util.LinkedHashMap$LinkedValues cannot be cast to java.util.ArrayList

使用map中的的map.values()方法返回值,返回类型是Collection,后面在接收的时候使用List进行的强转,

例如:

public Collection getItems() {
        return map.values();
    }

List cartItemList = (ArrayList) cart.gettems();

 

就会出现该异常:

java.util.LinkedHashMap$LinkedValues cannot be cast to java.util.ArrayList

解决:

其实在ArrayList中有一个构造器可以用构造器来接受Collection

ArrayList(Collection c)
Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.

即上面的例子改完之后就是如下:

List cartItemList = new ArrayList (cart.getItems());

问题就解决了

 

你可能感兴趣的:(java,错误信息)