通过ArrayList演示Collection接口

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

public class DemonstratedViaAnArrayListObject {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    // add elements in colors array to list
      String[] colors = {"BLACK", "RED", "WHITE", "BLUE", "CYAN"};
      List list = new ArrayList();      

      for (String color : colors)
         list.add(color); // adds color to end of list      

      // add elements in removeColors array to removeList
      String[] removeColors = {"RED", "WHITE", "BLUE"};
      List removeList = new ArrayList();

      for (String color : removeColors)
         removeList.add(color); 

      // output list contents
      System.out.println("ArrayList: ");

      for (int count = 0; count < list.size(); count++)
         System.out.printf("%s ", list.get(count));

      // remove from list the colors contained in removeList
      removeColors(list, removeList);

      // output list contents
      System.out.printf("%n%nArrayList after calling removeColors:%n");

      for (String color : list)
         System.out.printf("%s ", color);
}
// remove colors specified in collection2 from collection1
   private static void removeColors(Collection collection1, 
      Collection collection2)
   {
      // get iterator
      Iterator iterator = collection1.iterator(); 

      // loop while collection has items
      while (iterator.hasNext())         
      {
         if (collection2.contains(iterator.next()))
            iterator.remove(); // remove current element
      } 
   }

}
Console:
ArrayList:
BLACK RED WHITE BLUE CYAN

ArrayList after calling removeColors:
BLACK CYAN

你可能感兴趣的:(通过ArrayList演示Collection接口)