LinkedListlist = new LinkedList<>(); list.add("Hello"); list.add("World"); ListIterator iterator = list.listIterator(list.size()); while(iterator.hasPrevious()) { String value = iterator.previous(); System.out.println(value); }
ArrayListIn this code, we create an ArrayList, add three elements to it, and then create a listIterator starting at the beginning of the list. We then iterate through the list using the iterator's hasNext() method to check if there is a next element, and using the next() method to get the next element. If the element is equal to 2, we modify it using the iterator's set() method. This will change the ArrayList to [1, 4, 3] and output it.list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); ListIterator iterator = list.listIterator(); while(iterator.hasNext()) { int value = iterator.next(); if(value == 2) { iterator.set(4); } } System.out.println(list);