Java ArrayList traversal modification code example analysis

When using for-each to traverse the ArrayList while modifying:

public static void main(String[] args) {
    ArrayList<String> list = new ArrayList<>();
    list.add("aa");
    list.add("bb");
    list.add("cc");
    list.add("dd");
    System.out.println(list);

    for (String s : list) {
      if (s.equals("dd")) {
        list.remove(s);
      }
    }
    System.out.println(list);
  }

Will report an error

You can use the following methods instead:

① Use iterator to traverse and delete

public static void main(String[] args) {
    ArrayList<String> list = new ArrayList<>();
    list.add("aa");
    list.add("bb");
    list.add("cc");
    list.add("dd");
    System.out.println(list);

    Iterator<String> iterator = list.iterator();
    while (iterator.hasNext()) {
      String next = iterator.next();
      if (next.equals("dd")) {
        iterator.remove();
      }
    }
    System.out.println(list);
}

②: Use the most primitive for loop

public static void main(String[] args) {
    ArrayList<String> list = new ArrayList<>();
    list.add("aa");
    list.add("bb");
    list.add("cc");
    list.add("dd");
    System.out.println(list);
    
    for (int i = 0; i < list.size(); i++) {
      String s = list.get(i);
      if (s.equals("dd")) {
        list.remove(s);
      }
    }
    System.out.println(list);
}

③: Use the new method removeIf in jdk8 Collection (personal recommendation, simple and fast new features)

public static void main(String[] args) {
    ArrayList<String> list = new ArrayList<>();
    list.add("aa");
    list.add("bb");
    list.add("cc");
    list.add("dd");
    System.out.println(list);

    list.removeIf(next -> next.equals("dd"));
    System.out.println(list);
}

Some high-frequency interview questions collected in the latest 2020 (all organized into documents), there are many dry goods, including mysql, netty, spring, thread, spring cloud, jvm, source code, algorithm and other detailed explanations, as well as detailed learning plans, interviews Question sorting, etc. For those who need to obtain these contents, please add Q like: 11604713672

Guess you like

Origin blog.csdn.net/weixin_51495453/article/details/113854913