java.lang.ClassCastException:创建一个同步的链接列表 [英] java.lang.ClassCastException: Creating a synchronized Linked List

查看:273
本文介绍了java.lang.ClassCastException:创建一个同步的链接列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I want a synchronized LinkedList with a Generic Class A, here the relevant parts:

我想要一个具有泛型类A的同步LinkedList,这里是相关部分: B个实现Runnable {

public abstract class A<T extends B> implements Runnable {

而B的接口,其中真实B将是一个超类

And the interface for B, where the "real" B, will be a supclass

public interface B{

以下设置会引发运行时错误:

Following setup will throw a runtime error:

LinkedList<A<? extends B>> eopList = (LinkedList<A<? extends B>>) Collections
            .synchronizedCollection(new LinkedList<A<? extends B>>());

我发现了以下建议,但它也无法编译:

I've found the following proposal, but it also won't compile:

LinkedList<A<? extends B>> eopList = (LinkedList) Collections
            .synchronizedCollection(new LinkedList<A<? extends B>>());

这是日志:

Exception in thread "main" java.lang.ClassCastException: java.util.Collections$SynchronizedCollection cannot be cast to java.util.LinkedList


推荐答案

使用 Collections.synchronizedList() 方法。该方法返回一个 List< T> 。因此,将LHS上的类型设置为 List ,以避免类型转换:

Use Collections.synchronizedList() method instead. The method returns a List<T>. So, make the type on LHS as List, to avoid typecast:

List<A<? extends B>> eopList = Collections.synchronizedList(new LinkedList<A<? extends B>>());

这篇关于java.lang.ClassCastException:创建一个同步的链接列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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