Loop to drop four ways a list of elements

method one:

/**
  * Direct use foreach method to remove elements in the list will throw an exception
  * Exception in thread "main" java.util.ConcurrentModificationException
  * The problem with this approach is that, after deleting an element, list the size of the changes, and your index is changing,
  * So will cause you to miss some elements when traversal.
  * For example, when you delete the first element, while the index based on continued access to the first two elements, because the deletion of the back of the relationship between the elements are moved forward one,
  * The actual visit is the third element.
  * Accordingly, this approach can be used to delete a specific element used, but is not suitable for use when a plurality of loop elements deleted.
  */
public static void main(String[] args) {
    List<String> list = new ArrayList<>();
    list.add("aa");
    list.add("bb");
    list.add("cc");
    for (String str : list) {
        if ("aa".equals(str)) {
            list.remove(str);
        }
    }
    System.out.println(list.size());
}

Second way:

public static void main(String[] args) {
    List<String> list = new ArrayList<>();
    list.add("aa");
    list.add("bb");
    list.add("cc");
    Iterator<String> it = list.iterator();
    while(it.hasNext()){
        String str = (String)it.next();
        if("aa".equals(str)){
            it.remove();
        }
    }
    System.out.println(list.size());
}

Three ways:

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

Four ways:

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

Guess you like

Origin www.cnblogs.com/JimmyThomas/p/12105266.html