简体   繁体   English

投射同步的LinkedList时出错

[英]error while casting a synchronized LinkedList

I have a simple code: 我有一个简单的代码:

private List<String> requests = Collections.synchronizedList(new LinkedList<String>());

and

synchronized (requests) {
    ((LinkedList<String>)requests).addLast(message);
}

at runtime I get this error: 在运行时我收到此错误:

FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method of the activity
    at android.view.View$1.onClick(View.java:2144)
    at android.view.View.performClick(View.java:2485)
    at android.view.View$PerformClick.run(View.java:9080)
    at android.os.Handler.handleCallback(Handler.java:587)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:123)
    at android.app.ActivityThread.main(ActivityThread.java:3683)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:507)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
    at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:507)
    at android.view.View$1.onClick(View.java:2139)
    ... 11 more
Caused by: java.lang.ClassCastException: java.util.Collections$SynchronizedList
    at com.countryst.nabard.turnbased.client.networking.ClientNetworking.login(ClientNetworking.java:72)
    at com.countryst.nabard.turnbased.client.MainActivity.loginToServer(MainActivity.java:87)
    at com.countryst.nabard.turnbased.client.MainActivity.onButtonClicked(MainActivity.java:217)
    ... 14 more

This is part of an android program, I have similar code in my plain java code and works fine. 这是android程序的一部分,我在普通的Java代码中也有类似的代码,并且工作正常。

synchronizedList doesn't document that it will return something that can be cast back to the underlying list, just that it returns something that implements List<E> that is synchronized. synchronizedList并没有说明它将返回可以返回到基础列表的内容,而只是返回实现了已同步的List<E>内容。

If you need to use methods specific to LinkedList , keep a reference to the original list: 如果需要使用特定于LinkedList方法,请保留对原始列表的引用:

private LinkedList<String> requestsLinkedList = new LinkedList<String>();
private List<String> requests = Collections.synchronizedList(requestsLinkedList);

and then synchronize like this: 然后像这样同步:

synchronized (requests) {
    requestsLinkedList.addLast(message);
}

But in this case, you don't need to, because LinkedList#addLast is equivalent to List#add . 但是在这种情况下,您不需要这样做,因为LinkedList#addLastList#add等效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM