COP 3530 Section U03 Spring 2017 The Collection Interface ======================== Here is an example of how we can use the Collection interface. // test collection import java.util.*; public class Fall14TestCollection { public static void main(String[] args) { System.out.println("Test the Collection Interface"); System.out.println("=============================\n\n"); // test the printing System.out.println("We first test the printing."); System.out.println("We form an array list with the names Bill, Mark, Ana."); ArrayList friends = new ArrayList(); friends.add("Bill"); friends.add("Mark"); friends.add("Ana"); friends.add("Gandpa"); System.out.println("\nThe list of friends:"); printCollection(friends); System.out.println("\nWe form a set of the integers 7, 3, 5."); TreeSet integers = new TreeSet(); integers.add(7); integers.add(3); integers.add(5); System.out.println("\nThe tree of integers:"); printCollection(integers); // form a linked list of names System.out.println("\nWe form a linked list of new friends."); LinkedList newFriends = new LinkedList<>(); newFriends.add("Tornado"); newFriends.addFirst("Shrek"); newFriends.add("Cortadito"); System.out.println("\nWe print the new friends."); printCollection(newFriends); System.out.println("\nWe add the new friends to the array of friends."); friends.addAll(newFriends); System.out.println("\nWe print the updated friends array list."); printCollection(friends); } // print a collection using an iterator public static void printCollection( Collection c) { Iterator itr = c.iterator(); while (itr.hasNext()) { System.out.println(itr.next()); } } } The output: run: Test the Collection Interface ============================= We first test the printing. We form an array list with the names Bill, Mark, Ana. The list of friends: Bill Mark Ana Gandpa We form a set of the integers 7, 3, 5. The tree of integers: 3 5 7 We form a linked list of new friends. We print the new friends. Shrek Tornado Cortadito We add the new friends to the array of friends. We print the updated friends array list. Bill Mark Ana Gandpa Shrek Tornado Cortadito BUILD SUCCESSFUL (total time: 0 seconds)