当前位置: 代码迷 >> 综合 >> 异常转化问题: java.util.LinkedHashMap$LinkedValues cannot be cast to java.util.ArrayList
  详细解决方案

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

热度:40   发布时间:2023-12-14 16:55:01.0

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

例如:

public Collection<CartItem> getItems() {return map.values();}List<CartItem> cartItemList = (ArrayList<CartItem>) cart.gettems();

 

就会出现该异常:

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

解决:

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

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

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

List<CartItem> cartItemList = new ArrayList<CartItem> (cart.getItems());

问题就解决了

 

  相关解决方案