1

我想将特定元素从其原始位置移动到第 0 个索引。我尝试了以下

private void reoderArrayList() {
    Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
    mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);

    List<ResolveInfo> list = getPackageManager().queryIntentActivities( mainIntent, 0);
    Collections.sort(list, new ResolveInfo.DisplayNameComparator( getPackageManager()));
    if (list != null && !list.isEmpty()) {
                for(ResolveInfo resolveInfo : list){
            List<ResolveInfo> applist = getAppList();
            if (applist != null && !applist.isEmpty()) {

                for(ResolveInfo info : applist){
                    if(resolveInfo.activityInfo.applicationInfo.packageName.equals(info.packageName)){
                        list.remove(resolveInfo);
                        list.add(0,resolveInfo);
                    }
                }
            }

        }
        for (ResolveInfo resolveInfo : list) {
         //do something
        }
    }
}

我想将指定的元素移动到第 0 个位置,并将第 0 个位置的前一个元素移动到索引 1,依此类推。doInBackground() 我从AsyncTask 中调用了此方法。但这给出了以下异常。

 FATAL EXCEPTION: AsyncTask #1
 java.lang.RuntimeException: An error occured while executing doInBackground()
    at android.os.AsyncTask$3.done(AsyncTask.java:200)
    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
    at java.lang.Thread.run(Thread.java:1096)
 Caused by: java.util.ConcurrentModificationException

如何处理这个异常?

提前致谢

4

2 回答 2

0

尝试这个

 List<ResolveInfo> templist=new ArrayList<ResolveInfo>();
 ResolveInfo info=new ResolveInfo();

在for循环中添加这样

info=resolveInfo;

然后在forloop之外这样做

templist.addAll(list);
templist.remove(info);
list.clear();
list.add(info);
list.addAll(templist);
于 2013-05-17T04:58:36.957 回答
0
for(ResolveInfo info : applist){
                    if(resolveInfo.activityInfo.applicationInfo.packageName.equals(info.packageName)){
                        list.remove(resolveInfo);
                        list.add(0,resolveInfo);
                    }
                }

你不应该这样做。而是使用迭代器。

Iterator iterator = applist.iterator();
while(iterator.moveToNext()){
iterator.remove();
//Do other stuff over here.
}

原因是在循环遍历数组时不能从数组中删除。

于 2013-05-17T04:36:10.817 回答