相关疑难解决方法(0)

如何在Java中修改对象时迭代它?

可能重复:
Java:高效等效于在迭代集合时删除从迭代中
删除集合中的项目

我试图循环HashMap:

Map<String, Integer> group0 = new HashMap<String, Integer>();
Run Code Online (Sandbox Code Playgroud)

...并提取每个元素group0.这是我的方法:

// iterate through all Members in group 0 that have not been assigned yet
for (Map.Entry<String, Integer> entry : group0.entrySet()) {

    // determine where to assign 'entry'
    iEntryGroup = hasBeenAccusedByGroup(entry.getKey());
    if (iEntryGroup == 1) {
        assign(entry.getKey(), entry.getValue(), 2);
    } else {
        assign(entry.getKey(), entry.getValue(), 1);
    }
}
Run Code Online (Sandbox Code Playgroud)

这里的问题是每次调用assign()都会从中删除元素group0,从而修改其大小,从而导致以下错误:

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793)
    at java.util.HashMap$EntryIterator.next(HashMap.java:834)
    at java.util.HashMap$EntryIterator.next(HashMap.java:832) …
Run Code Online (Sandbox Code Playgroud)

java exception hashmap concurrentmodification

5
推荐指数
1
解决办法
1万
查看次数

从List中动态删除元素

我在迭代列表时删除列表元素时遇到问题.码:

For (WebElement element: list){
    if (!element.isEnabled() || !element.isSelected()){
        list.remove(element);
    }
}
Run Code Online (Sandbox Code Playgroud)

我得到了一个ConcurrentModificationException,我完全理解.我在循环列表中删除列表中的项目.直觉上,这会搞砸循环的索引.

我的问题是,怎么回事我应该删除或者不元素enabledselected从这个名单?

java arraylist

5
推荐指数
2
解决办法
4605
查看次数

LinkedList迭代器删除

可能重复:
在迭代Collection时删除元素的高效等效项

private LinkedList flights;
Run Code Online (Sandbox Code Playgroud)

....

public void clear(){

    ListIterator itr = flights.listIterator();

    while(itr.hasNext()){


        flights.remove(itr.next());

    }

}
Run Code Online (Sandbox Code Playgroud)

....

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.LinkedList$ListItr.checkForComodification(Unknown Source)
    at java.util.LinkedList$ListItr.next(Unknown Source)
    at section1.FlightQueue.clear(FlightQueue.java:44)
    at section1.FlightTest001.main(FlightTest001.java:22)
Run Code Online (Sandbox Code Playgroud)

它出什么问题了?不能理解为什么会给出错误,我确信我在arraylists或数组上使用了相同的代码并且它已经有效了.

java iterator linked-list

5
推荐指数
1
解决办法
2万
查看次数

ConcurrentModificationException甚至在LinkedHashMap上使用Collections.sychronizedMap

我在我的类中使用了一个Map对象,我已经与LinkedHashMap的Collections.synchronizedMap()同步,如下所示:

private GameObjectManager(){
        gameObjects = Collections.synchronizedMap(new LinkedHashMap<String, GameObject>());
}
Run Code Online (Sandbox Code Playgroud)

我在这个函数的第三行得到一个并发修改异常:

public static void frameElapsed(float msElapsed){
    if(!INSTANCE.gameObjects.isEmpty()){
        synchronized(INSTANCE.gameObjects){
            for(GameObject object : INSTANCE.gameObjects.values()){...}
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在迭代Map的所有其他位置,我按照文档同步地图.

我的类中还有其他函数使用这个Map(同步的!)和put()和remove()对象,但这应该无关紧要.我究竟做错了什么?请询问更多代码,不知道还能提供什么.

哦,和日志消息:

08-20 15:55:30.109: E/AndroidRuntime(14482): FATAL EXCEPTION: GLThread 1748
08-20 15:55:30.109: E/AndroidRuntime(14482): java.util.ConcurrentModificationException
08-20 15:55:30.109: E/AndroidRuntime(14482):    at     java.util.LinkedHashMap$LinkedHashIterator.nextEntry(LinkedHashMap.java:350)
08-20 15:55:30.109: E/AndroidRuntime(14482):    at     java.util.LinkedHashMap$ValueIterator.next(LinkedHashMap.java:374)
08-20 15:55:30.109: E/AndroidRuntime(14482):    at     package.GameObjectManager.frameElapsed(GameObjectManager.java:247)
08-20 15:55:30.109: E/AndroidRuntime(14482):    at     package.GamekitInterface.render(Native Method)
08-20 15:55:30.109: E/AndroidRuntime(14482):    at     package.GamekitInterface.renderFrame(GamekitInterface.java:332)
08-20 15:55:30.109: E/AndroidRuntime(14482):    at     com.qualcomm.QCARSamples.ImageTargets.GameEngineInterface.onDrawFrame(GameEngineInterface.java:107)
08-20 15:55:30.109: E/AndroidRuntime(14482):    at     android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1516)
08-20 15:55:30.109: E/AndroidRuntime(14482):    at     android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1240)
Run Code Online (Sandbox Code Playgroud)

java multithreading synchronized linkedhashmap concurrentmodification

5
推荐指数
1
解决办法
3282
查看次数

Java Arraylist通过索引删除多个元素

这是我的代码:

for (int i = 0; i < myarraylist.size(); i++) {
        for (int j = 0; j < stopwords.size(); j++) {
            if (stopwords.get(j).equals(myarraylist.get(i))) {
                myarraylist.remove(i);
                id.remove(i);
                i--; // to look at the same index again!
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

我有问题..删除元素后,所有索引总是改变,上面的循环太乱了.

为了说明:我有54个数据,但上面的循环在元素删除后变得混乱..因此只检查了50个数据.

有没有其他方法或修复我的代码以索引删除多个元素?元素索引对我来说非常重要,要删除具有相同索引的另一个arraylist.

java android arraylist stop-words

5
推荐指数
2
解决办法
2万
查看次数

在两个线程之间共享一个ArrayList?

所以我有两个线程在运行,其中一个线程应该从用户获取信息,另一个线程假设使用用户提供的信息,如下所示:

public class UserRequest implements Runnable {

@Override
public void run() {
    // TODO Auto-generated method stub
    String request;
    Scanner input = new Scanner(System.in);
    while(true)
    {
        System.out.println("Please enter request:");
        request = input.nextLine();
        try
        {
            //do something
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

第二个帖子:

public class Poller implements Runnable {

ArrayList<String> colors = new ArrayList<String>();

public void poll()
{
    for(String color : colors)
    {
        if(color == "")
        {
            //do work
        }
        else
        {
            //do work
        }
    }
}

@Override …
Run Code Online (Sandbox Code Playgroud)

java concurrency multithreading arraylist

5
推荐指数
1
解决办法
1813
查看次数

ConcurrentModificationException(Java)

Exception in thread "main" java.util.ConcurrentModificationException
Squash the PC dirties the room Violet. The room's state is now dirty
Lily the animal growls
The Animal Lily left the room and goes to Green through the west door.
        at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793)
        at java.util.HashMap$KeyIterator.next(HashMap.java:828)
        at homework5.Room.critReactRoomStateChange(Room.java:76)
        at homework5.PC.play(PC.java:121)
        at homework5.Main.main(Main.java:41)
Java Result: 1
Run Code Online (Sandbox Code Playgroud)

这是我收到的错误.

我的方法看起来像

public void critReactRoomStateChange(String command, PC pc) {
    Creature temp = null;
    Iterator iterator = getCreatures().keySet().iterator();
    while (iterator.hasNext()) {
        String names = iterator.next().toString();
        if (!(getCreatures().get(names) instanceof PC)) {
            temp = …
Run Code Online (Sandbox Code Playgroud)

java iterator concurrentmodification

4
推荐指数
1
解决办法
6286
查看次数

如何在修改列表时从列表中删除

我正在尝试创建一个霍夫曼树,并且正在尝试合并两棵树.我无法弄清楚如何在没有得到"并发修改异常"的情况下删除程序中的树,因为我正在迭代列表并尝试同时从列表中删除.

BinaryTree<Character, Integer> t1 = null;
        BinaryTree<Character, Integer> t2 = null;
        BinaryTree<Character, Integer> tFinal = null;
        int treeSize = TREES.size();

        for (int i = 0; i < treeSize; i++) {

            for (BinaryTree<Character, Integer> t : TREES) {
                System.out.println("treeSize " + treeSize);
                System.out.println(t.getRoot().getElement()
                        + "  t.getRoot().getElement()");

                // here I edited the merge function in Binary Tree to set
                // the new root
                // to have null value for value, and itemTwo for weight
                System.out.println(t.getRoot().getValue() + " weight of tree \n");
                t1 …
Run Code Online (Sandbox Code Playgroud)

java

4
推荐指数
1
解决办法
281
查看次数

在java中,多个线程在同一个字符串列表中工作?

我试图找出让多个线程在同一个字符串列表中工作的最佳方法.例如,假设我有一个单词列表,我想要多个线程来打印出这个列表中的每个单词.

这就是我想出的.该线程使用while循环,当迭代器具有next时,它会打印出来并从列表中删除它.

import java.util.*;
public class ThreadsExample {

    static Iterator it;

    public static void main(String[] args) throws Exception {

        ArrayList<String> list = new ArrayList<>();

        list.add("comet");
        list.add("planet");
        list.add("moon");
        list.add("star");
        list.add("asteroid");
        list.add("rocket");
        list.add("spaceship");
        list.add("solar");
        list.add("quasar");
        list.add("blackhole");


        it = list.iterator();

        //launch three threads
        RunIt rit = new RunIt();

        rit.runit();
        rit.runit();
        rit.runit();

    }
}

class RunIt implements Runnable {

    public void run()
    {
        while (ThreadsExample.it.hasNext()) {
            //Print out and remove string from the list
            System.out.println(ThreadsExample.it.next());

            ThreadsExample.it.remove();
        }
    }

    public void runit() {
        Thread thread …
Run Code Online (Sandbox Code Playgroud)

java string multithreading

4
推荐指数
1
解决办法
1672
查看次数

多个线程访问同一个集合时出现 ConcurrentModificationException

我有 2 个 Main 类的内部线程类。有时,当一个添加新元素而另一个被删除时,它会导致 ConcurrentModificationException。我想我不知道如何同步它们。

Class Main{
HashSet<MyObject> set;   
Thread A{
       run(running){
          ...
          set.add(obj);
          ...
       }
    }

Thread B{
     run(){
      while (running) {
                for (Iterator<MyObject> i = set.iterator(); i.hasNext();) {
                    MyObject obj= i.next();
                    if (!obj.isSmt()) {
                        i.remove();
                       ...
                    }
                }
            }
     }
}

}
Run Code Online (Sandbox Code Playgroud)

java

4
推荐指数
2
解决办法
4013
查看次数