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.
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()); }
(5) ArrayLists as Parameters
- An
parametercan be ofArrayListtype. - A returned value from a method can be of ArrayList type.
- If you pass an
ArrayListobjectas an argumentto a parameter of a method,changes will reflect on the ArrayList. - Example:
static void replace(ArrayList<Integer> list, int index, int value) { list.set(index, value); } public static void main(String[] args) { ArrayList<Integer> list1 = new ArrayList<Integer>(); list1.add(1); list1.add(2); // if you pass an ArrayList object as an argument to a parameter // of a method, changes will reflect on the ArrayList. System.out.println(list1); replace(list1, 0, 666); System.out.println(list1); }
(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.