1. Exam Points
Traverse ArrayListsusing loops (for, for-each, while).- Use ArrayList methods while traversing ArrayLists.
- Use a simplified
trace tableto track changes of an ArrayList.Do notadd or remove elements inside a for-each loop, it is not allowed.- If you try to
remove elements inside a loop, use a for loop, and remove reversely.- If you try to
remove elementsmeeting a certain condition from the first to the lastin a for loop, thenit only workswhen qualified elements arenot adjacent, for two adjacent elements, only the first one will be deleted.Note: pay attention how i changes: i++, i--, i+=2
2. Knowledge Points
(1) ArrayList Traversals
- You may traverse an ArrayList using:
- for loops (use indexes)
- while loops (use indexes)
- for-each loops (enhanced for loops) (no use of indexes)
- Attempting to access an index value outside of its range will result in an
IndexOutOfBoundsException. - Example: Traverse ArrayLists using
for loops
ArrayList<Integer> list1 = new ArrayList<Integer>(); list1.add(10); list1.add(20); list1.add(30); list1.add(40); ArrayList<String> list2 = new ArrayList<String>(); list2.add("Amy"); list2.add("Anna"); list2.add("David"); ArrayList<Dog> dogList = new ArrayList<Dog>(); dogList.add(new Dog("haha")); dogList.add(new Dog("lele")); dogList.add(new Dog("doudou")); // for loop: use indexes for (int i = 0; i < list1.size(); i++) { Integer x = list1.get(i); System.out.print(x + " "); } System.out.println(); for (int i = 0; i < list2.size(); i++) { String x = list2.get(i); System.out.print(x + " "); } System.out.println(); for (int i = 0; i < dogList.size(); i++) { Dog d = dogList.get(i); System.out.println(d.getName()); } - Example: Traverse ArrayLists using
for-each loops
// for-each loop: no need to use indexes for (Integer x : list1) { // x means the current element System.out.print(x + " "); } System.out.println(); for (String name : list2) { // x means the current element System.out.print(name + " "); } for(Dog x:dogList) { System.out.println(x.getName()); }
(2) Note
Changing the sizeof an ArrayList while traversing it using anenhanced for loopcan result in a ConcurrentModificationException.- Therefore, you should
not add or remove elementswhen using anenhanced for loopto traverse an ArrayList. - (Warning) If you try to remove elements that meet a certain condition from the first element to the last inside a for loop, then your algorithm will only work when all the qualified elements are not adjacent, and for two adjacent elements, only one of them will be deleted.
- Pay attention how i is changed: i++, i--, i+=2