gpt4 book ai didi

java - 尝试向 recyclerview 添加元素(ConcurrentModificationException)

转载 作者:行者123 更新时间:2023-12-01 21:27:14 24 4
gpt4 key购买 nike

我正在尝试将项目添加到列表中,但出现错误,我不知道如何解决它。
下面是添加的示例:

for (Object object : mData) {
if (object instanceof BaseAdapter.ChoseFriendItem) {
mAdapter.addItem(1, object);
}
}

其中 mDate - arraylist
执行代码后出现以下错误:

FATAL EXCEPTION: main
Process: com.akbars.bankok, PID: 15263 java.util.ConcurrentModificationException
at java.util.ArrayList$ArrayListIterator.next(ArrayList.java:573)
at com.akbars.bankok.v2.ActivityChoseFriends.onClick(ActivityChoseFriends.java:311)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

然后我尝试使用迭代器。但为什么它只添加一个元素而不是从列表的开头添加,这是一个例子:

for (ListIterator<Object> iterator = mData.listIterator(); iterator.hasNext();) {
if (iterator.next() instanceof BaseAdapter.ChoseFriendItem){
mAdapter.addItem(1, iterator.next());
return;
}
}

也许有人知道如何修复这个错误?

最佳答案

这段代码你的代码应该是这样的:

for (ListIterator<Object> iterator = mData.listIterator(); iterator
.hasNext();) {
Object item = iterator.next();
if (item instanceof BaseAdapter.ChoseFriendItem){
mAdapter.addItem(1, item);
//return; There should be no return statement here.
}
}

You called iterator.next() two times which will one element each time and give incorrect results.

关于java - 尝试向 recyclerview 添加元素(ConcurrentModificationException),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37930336/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com