我正在以下列方式在我的应用中向/从ArrayLists添加/删除项目:
public long gotoItem(int pos) {
if (pos > 0) {
List<QueueItem> mSubList = mItems.subList(0, pos);
switch (mRepeatType) {
case NO_REPEAT:
case REPEAT_SINGLE:
mPlayedItems.addAll(mSubList);
mItems.removeAll(mSubList);
break;
case REPEAT_ALL:
mItems.removeAll(mSubList);
mItems.addAll(mSubList);
break;
}
}
return (long) mItems.get(0).getItem();
}
我抛出了以下异常:
> java.util.ConcurrentModificationException at java.util.AbstractList$SubAbstractList.listIterator(AbstractList.java:314)
at java.util.AbstractList$SubAbstractList.iterator(AbstractList.java:301)
at java.util.AbstractCollection.contains(AbstractCollection.java:127)
at java.util.AbstractCollection.removeAll(AbstractCollection.java:277)
at at.guger.musixs.playback.queue.Queue.gotoItem(Queue.java:135)
at at.guger.musixs.playback.MusicService.gotoPosition(MusicService.java:500)
at at.guger.musixs.playback.MusicPlayer.gotoPosition(MusicPlayer.java:138)
at at.guger.musixs.activity.MainActivity.SyncLocation(MainActivity.java:707)
at at.guger.musixs.activity.MainActivity.access$200(MainActivity.java:73)
at at.guger.musixs.activity.MainActivity$1.onServiceConnected(MainActivity.java:605)
at at.guger.musixs.playback.MusicPlayer$ServiceBinder.onServiceConnected(MusicPlayer.java:246)
at android.app.LoadedApk$ServiceDispatcher.doConnected(LoadedApk.java:1224)
at android.app.LoadedApk$ServiceDispatcher$RunConnection.run(LoadedApk.java:1241)
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:5461)
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)
为什么会出现此错误,如何以最简单的方式修复此错误? - 我是否真的必须从arraylists中删除(并添加)项目?
谢谢!
答案 0 :(得分:4)
SubList
实际上是原始列表顶部的视图。在内部,它仍然保留原始列表。因此,当您在内部调用originalList.removeAll(subList)
时,它实际上会迭代原始列表并尝试修改它。这就是你获得ConcurrentModificationException
的原因
一个简单的解决方案是将子列表复制到新列表(简化示例):
List<QueueItem> subList = new ArrayList<>(items.subList(0, pos));
items.removeAll(subList);