Guest User

Untitled

a guest
Nov 24th, 2017
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.86 KB | None | 0 0
  1. import java.util.Collection;
  2. import java.util.ArrayList;
  3. import java.util.Iterator;
  4.  
  5. public class Dog {
  6.     public String name;
  7.    
  8.     public Dog(String newName){
  9.         name = newName;
  10.     }
  11.    
  12.     public String toString(){
  13.         return name;
  14.     }
  15.    
  16.     public void printDog(){
  17.         System.out.printf("%s\n", name);
  18.     }
  19. }
  20.  
  21.  
  22. class Dogs {
  23.     public static void main(String[] args) {        
  24.          Collection<Dog> pack = new ArrayList<Dog>();
  25.          pack.add(new Dog("Fido"));
  26.          pack.add(new Dog("Spot"));
  27.          pack.add(new Dog("Lucy"));
  28.          System.out.println(pack);
  29.          
  30.          for (Dog singleDog : pack){
  31.              System.out.println(singleDog.toString());
  32.          }
  33.          
  34.          for(Iterator<Dog> dogIter = pack.iterator(); dogIter.hasNext();)
  35.          {
  36.              Dog singleDog = dogIter.next();
  37.              if (singleDog.toString().equals("Spot")){
  38.                 //1. pack.add(new Dog("Rin-Tin-Tin")); THIS FAILS
  39.                 //2. dogIter.add(new Dog("Some new dog")); THIS FAILS
  40.                 //3.
  41.                 pack.remove(singleDog); //THIS SUCCESSFULLY REMOVES SPOT FROM PACK
  42.                 //4. dogIter.remove(singleDog); THIS FAILS
  43.              }
  44.              
  45.          }
  46.          
  47.          for (Dog singleDog : pack){
  48.              System.out.println(singleDog);
  49.          }
  50.          
  51.                  
  52.                      
  53.     }
  54.    
  55. }
  56. /*
  57. 1.  Adding to the collection that we are iterating over results in this error:
  58. Exception in thread "main" java.util.ConcurrentModificationException
  59.     at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
  60.     at java.util.ArrayList$Itr.next(Unknown Source)
  61.     at Dogs.main(Dog.java:36)
  62.  
  63. 2.  You cannot add to an iterator
  64.  
  65. 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
  66.  
  67. 4.  You cannot remove from an iterator
  68. */
Add Comment
Please, Sign In to add comment