从Java数组中移除元素会引发异常。

huangapple 未分类评论60阅读模式
英文:

Removing elements from array in java throws exception

问题

我对Java还很新,仍在努力理解这里的数组工作方式。以下代码,我原以为会打印出 "2":

   import java.util.ArrayList;

   public static void main(String[] args) {

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

      myArray.add("1");
      myArray.add("2");
      myArray.add("1");
      myArray.add("1");

      for (String s: myArray){
        if(s.equals("1"))
          myArray.remove(s);
      }

      for (String s: myArray) {
         System.out.println(s);
      }
   }

在执行时抛出以下异常:

Exception in thread "main" java.util.ConcurrentModificationException
	at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1042)
	at java.base/java.util.ArrayList$Itr.next(ArrayList.java:996)
	at ex.main(ex.java:40)

就像我所说的,这可能是一个愚蠢的问题,但是我这有限的经验无法看出这里发生了什么。

非常感谢您的帮助。

英文:

I'm quite new to java and I'm still trying to figuring out how arrays work here. The following code, which I thought would print "2":

   import java.util.ArrayList;

   public static void main(String[] args) {

      ArrayList&lt;String&gt; myArray = new ArrayList&lt;String&gt;();

      myArray.add(&quot;1&quot;);
      myArray.add(&quot;2&quot;);
      myArray.add(&quot;1&quot;);
      myArray.add(&quot;1&quot;);

      for (String s: myArray){
        if(s == &quot;1&quot;)
          myArray.remove(s);
      }

      for (String s: myArray) {
         System.out.println(s);
      }
   }

Throws this exception when executing:

Exception in thread &quot;main&quot; java.util.ConcurrentModificationException
	at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1042)
	at java.base/java.util.ArrayList$Itr.next(ArrayList.java:996)
	at ex.main(ex.java:40)

As I said this might be a stupid question, but my unexperienced eyes just can't see what is happening here.

Thank you all in advance.

huangapple
  • 本文由 发表于 2020年3月15日 21:49:39
  • 转载请务必保留本文链接:https://java.coder-hub.com/60693589.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定