ArrayList: deletes elements and arraylist elements.
1. Use a for loop (only progressive traversal is allowed)
public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("111"); list.add("222"); list.add("333"); list.add("222"); list.add("444"); for (int i = list.size() - 1; i >= 0; i--) { if ("222".equals((String)list.get(i))) { list.remove(i); System.out.println(list.get(i)); } } System.out.println("=========" + list.size()); for (String str : list) { System.out.println(str); } }
Running result:
222
222
=========== 3
111
333
444
2. Use the iterator to delete elements:
public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("111"); list.add("222"); list.add("333"); list.add("222"); list.add("444"); Iterator<String> itr = list.iterator(); while (itr.hasNext()) { String str = itr.next(); if ("333".equals(str)) { itr.remove(); } } for (String str : list) { System.out.println(str); } }
Running result:
111
222
222
444
E |
remove(int index) Removes the element at the specified position from the list. |
boolean |
remove(Object o) Remove the specified Element (if any) that appears for the first time from the list ). |
List. remove (2 );
List. remove ("222 ");
Both methods can be used independently, instead of being used only during the time period.