Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Collection;
- import java.util.ArrayList;
- import java.util.Iterator;
- public class Dog {
- public String name;
- public Dog(String newName){
- name = newName;
- }
- public String toString(){
- return name;
- }
- public void printDog(){
- System.out.printf("%s\n", name);
- }
- }
- class Dogs {
- public static void main(String[] args) {
- Collection<Dog> pack = new ArrayList<Dog>();
- pack.add(new Dog("Fido"));
- pack.add(new Dog("Spot"));
- pack.add(new Dog("Lucy"));
- System.out.println(pack);
- for (Dog singleDog : pack){
- System.out.println(singleDog.toString());
- }
- for(Iterator<Dog> dogIter = pack.iterator(); dogIter.hasNext();)
- {
- Dog singleDog = dogIter.next();
- if (singleDog.toString().equals("Spot")){
- //1. pack.add(new Dog("Rin-Tin-Tin")); THIS FAILS
- //2. dogIter.add(new Dog("Some new dog")); THIS FAILS
- //3.
- pack.remove(singleDog); //THIS SUCCESSFULLY REMOVES SPOT FROM PACK
- //4. dogIter.remove(singleDog); THIS FAILS
- }
- }
- for (Dog singleDog : pack){
- System.out.println(singleDog);
- }
- }
- }
- /*
- 1. Adding to the collection that we are iterating over results in this error:
- Exception in thread "main" java.util.ConcurrentModificationException
- at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
- at java.util.ArrayList$Itr.next(Unknown Source)
- at Dogs.main(Dog.java:36)
- 2. You cannot add to an iterator
- 3. Removing the dog Spot from the collection is allowed, then printing the list after the for loop results in only Fido and Lucy being contained in the list
- 4. You cannot remove from an iterator
- */
Add Comment
Please, Sign In to add comment