Computer Science 15-100, Fall 2008
Class Notes: Getting Started with the Java Collection Framework
Getting Started with the JCF (Java Collection Framework)
import java.util.*; class MyCode { public static void main(String[] args) { System.out.println("This code demonstrates an ArrayList, which is"); System.out.println("basically a variable-sized array."); // Construct an ArrayList System.out.println("Calling constructor:"); ArrayList<String> list = new ArrayList<String>(); // Print (with implicit toString) print(list); // see helper method below // Add elements System.out.println("Adding Dog and Cat:"); list.add("Dog"); // add Dog to end of list list.add("Cat"); // add Cat to end of list print(list); // Add an element at a specific location System.out.println("Adding Cow at Index 1:"); list.add(1,"Cow"); // add Cow at index 1 print(list); // Add all elements from another collection (such as another list) System.out.println("Adding Frog and Bird:"); ArrayList<String> frogAndBird = new ArrayList<String>(); frogAndBird.add("Frog"); frogAndBird.add("Bird"); list.addAll(frogAndBird); // add all elements from another list print(list); // Add all elements from another list at a specific location System.out.println("Adding Frog and Bird again at Index 1:"); list.addAll(1, frogAndBird); // add all elements at index 1 print(list); // Getting and setting a specific element System.out.println("Setting element 6 to Cow:"); System.out.println(" before: list.get(6) = " + list.get(6)); list.set(6, "Cow"); // set element at index 6 to "Cow" System.out.println(" after: list.get(6) = " + list.get(6)); print(list); // Other accessors (contains, indexOf, lastIndexOf) System.out.println("Other accessors:"); System.out.println(" list.contains(\"Cow\") = " + list.contains("Cow")); System.out.println(" list.contains(\"Ant\") = " + list.contains("Ant")); System.out.println(" list.indexOf(\"Cow\") = " + list.indexOf("Cow")); System.out.println(" list.indexOf(\"Ant\") = " + list.indexOf("Ant")); System.out.println(" list.lastIndexOf(\"Cow\") = " + list.lastIndexOf("Cow")); System.out.println(" list.lastIndexOf(\"Ant\") = " + list.lastIndexOf("Ant")); // remove first occurrence of an element System.out.println("Removing first Cow:"); list.remove("Cow"); // remove first occurrence of "Cow" from list print(list); // remove element at a specific location System.out.println("Removing element at index 1:"); list.remove(1); // remove element at index 1 from list print(list); // Clear list System.out.println("Clearing the list:"); list.clear(); // clear the list (remove all elements from it) print(list); } // Helper method to print the list and some info about it public static void print(ArrayList<String> list) { System.out.print(" list=" + list.toString()); System.out.print(" size=" + list.size()); System.out.print(" isEmpty=" + list.isEmpty()); System.out.println(); } }
import java.util.*; class MyCode { public static void main(String[] args) { System.out.println("This code demonstrates a HashSet, which is"); System.out.println("similar to an ArrayList, except that it may not"); System.out.println("contain two copies of equal values, and there is"); System.out.println("no guarantee of the order of the set's elements."); // Construct a HashSet System.out.println("Calling constructor:"); HashSet<String> set = new HashSet<String>(); // Print (with implicit toString) print(set); // see helper method below // Add elements System.out.println("Adding Dog and Cat:"); set.add("Dog"); // add Dog to set set.add("Cat"); // add Cat to set print(set); // Add elements with duplicates System.out.println("Adding Frog and Cat:"); set.add("Frog"); // add Frog to set set.add("Cat"); // add Cat to set print(set); // Add all elements from another collection (say, a list) System.out.println("Adding Frog and Bird:"); ArrayList<String> frogAndBird = new ArrayList<String>(); frogAndBird.add("Frog"); frogAndBird.add("Bird"); set.addAll(frogAndBird); // add all elements from a list print(set); // Other accessors (just contains): System.out.println("Other accessors (just contains):"); System.out.println(" set.contains(\"Dog\") = " + set.contains("Dog")); System.out.println(" set.contains(\"Ant\") = " + set.contains("Ant")); // remove an element System.out.println("Removing Dog:"); set.remove("Dog"); // remove "Dog" from set print(set); // Clear set System.out.println("Clearing the set:"); set.clear(); // clear the list (remove all elements from it) print(set); } // Helper method to print the list and some info about it public static void print(HashSet<String> set) { System.out.print(" set=" + set.toString()); System.out.print(" size=" + set.size()); System.out.print(" isEmpty=" + set.isEmpty()); System.out.println(); } }
import java.util.*; class MyCode { public static void main(String[] args) { System.out.println("This code demonstrates a HashMap, which maps"); System.out.println("keys to values. Note that the keys form a Set,"); System.out.println("which means the map cannot contain two copies"); System.out.println("of equal keys, and there are no guarantees"); System.out.println("of the order in which keys occur."); System.out.println(); // Construct a HashMap System.out.println("Calling constructor:"); HashMap<String, String> map = new HashMap<String, String>(); // Print (with implicit toString) print(map); // see helper method below // Add elements (key-value pairs) System.out.println("Mapping Paris to Texas, and Ankara to Turkey:"); map.put("Paris", "Texas"); map.put("Ankara", "Turkey"); print(map); // Add elements with duplicate keys System.out.println("Mapping Paris to France, and Doha to Qatar:"); map.put("Paris", "France"); map.put("Doha", "Qatar"); print(map); // Other accessors (get, containsKey, and keySet): System.out.println("Other accessors (get and containsKey):"); System.out.println(" map.get(\"Paris\") = " + map.get("Paris")); System.out.println(" map.get(\"London\") = " + map.get("London")); System.out.println(" map.containsKey(\"Paris\") = " + map.containsKey("Paris")); System.out.println(" map.containsKey(\"London\") = " + map.containsKey("London")); System.out.println(" map.keySet() = " + map.keySet()); // remove a key (and its mapped value) System.out.println("Removing Paris:"); map.remove("Paris"); // remove "Paris" key (and its value) from map print(map); // Clear map System.out.println("Clearing the map:"); map.clear(); // clear the map (remove all key-value pairs from it) print(map); } // Helper method to print the list and some info about it public static void print(HashMap<String, String> map) { System.out.print(" map=" + map.toString()); System.out.print(" map=" + map.size()); System.out.print(" isEmpty=" + map.isEmpty()); System.out.println(); } }
import java.util.*; class MyCode { public static void main(String[] args) { System.out.println("This code demonstrates static methods from the"); System.out.println("Collections class, which provides helpful utilities"); System.out.println("for Lists (and other Collections) in the same way"); System.out.println("that the Arrays class does for arrays."); System.out.println(); // Construct an ArrayList and add some values System.out.println("Constructing a list and adding Dow, Cow, and Bird"); ArrayList<String> list = new ArrayList<String>(); list.add("Cow"); list.add("Dog"); list.add("Bird"); list.add("Ant"); print(list); // First test of (broken) binarySearch over unsorted list System.out.println("Broken binarySearch in unsorted list:"); System.out.println(" Collections.binarySearch(\"Ant\") = " + Collections.binarySearch(list, "Ant")); // Sort the list System.out.println("Sorting the list:"); Collections.sort(list); print(list); // Second test of (working) binarySearch over sorted list System.out.println("Working binarySearch in sorted list:"); System.out.println(" Collections.binarySearch(\"Ant\") = " + Collections.binarySearch(list, "Ant")); System.out.println(" Collections.binarySearch(\"Frog\") = " + Collections.binarySearch(list, "Frog")); // Reverse the list System.out.println("Reversing the list:"); Collections.reverse(list); print(list); // Rotate the list System.out.println("Rotating the list 1 to the right:"); Collections.rotate(list, 1); print(list); System.out.println("Rotating the list 3 to the right:"); Collections.rotate(list, 3); print(list); // Shuffle the list System.out.println("Shuffling the list a few times:"); Collections.shuffle(list); print(list); Collections.shuffle(list); print(list); Collections.shuffle(list); print(list); } // Helper method to print the list and some info about it public static void print(ArrayList<String> list) { System.out.println(" list=" + list.toString()); } }
import java.util.*; class MyCode { public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>(); list.add("Fred"); System.out.println(list); String[] moreNames = { "Wilma", "Barney", "Betty" }; // try (and fail) to add all the names in the array to the list list.addAll(moreNames); // will not compile! System.out.println(list); } }
Fixed With Arrays.asList
import java.util.*; class MyCode { public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>(); list.add("Fred"); System.out.println(list); String[] moreNames = { "Wilma", "Barney", "Betty" }; // Add all the names in the array to the list list.addAll(Arrays.asList(moreNames)); // works! System.out.println(list); } }
import java.util.*; class MyCode { public static void main(String[] args) { System.out.println("Demo calling some of the Collections methods"); System.out.println("using an array and Arrays.asList. This demo shows"); System.out.println("just a few methods, but the technique works in general."); System.out.println(); String[] a = { "Fred", "Wilma", "Barney", "Betty" }; System.out.print("Using List's toString method:"); System.out.println(Arrays.asList(a)); System.out.print("Max value in array: " ); System.out.println(Collections.max(Arrays.asList(a))); System.out.print("Min value in array: "); System.out.println(Collections.min(Arrays.asList(a))); System.out.print("Reversed array:"); Collections.reverse(Arrays.asList(a)); System.out.println(Arrays.asList(a)); System.out.print("Verify we modified the actual array: "); System.out.println(Arrays.toString(a)); } }
import java.util.*; class MyCode { public static void main(String[]args){ int[] a = {1, 2, 3}; Collections.reverse(Arrays.asList(a)); // Fails!!! (quietly, too) System.out.println(Arrays.toString(a)); Integer[] b = {1, 2, 3}; Collections.reverse(Arrays.asList(b)); // Works!!! System.out.println(Arrays.toString(b)); } }
import java.util.*; class MyCode { // Helper method to support using int arrays as Lists public static List<Integer> intArrayAsList(final int[] a) { return new AbstractList<Integer>() { public Integer get(int i) { return a[i]; } public Integer set(int i, Integer val) { int old=a[i]; a[i]=val; return old;} public int size() { return a.length; } }; } public static void main(String[]args){ int[] a = {1, 2, 3}; Collections.reverse(intArrayAsList(a)); // Works with helper method! System.out.println(Arrays.toString(a)); Integer[] b = {1, 2, 3}; Collections.reverse(Arrays.asList(b)); // Still works!!! System.out.println(Arrays.toString(b)); } } Another Example (for doubles): import java.util.*; class MyCode { // Helper method to support using int arrays as Lists public static List<Double> doubleArrayAsList(final double[] a) { return new AbstractList<Double>() { public Double get(int i) { return a[i]; } public Double set(int i, Double val) { double old=a[i]; a[i]=val; return old;} public int size() { return a.length; } }; } public static void main(String[]args){ double[] a = {1.2, 3.4, 5.6}; Collections.reverse(doubleArrayAsList(a)); // Works with helper method! System.out.println(Arrays.toString(a)); Double[] b = {1.2, 3.4, 5.6}; Collections.reverse(Arrays.asList(b)); // Still works!!! System.out.println(Arrays.toString(b)); } }
import java.util.*; class MyCode { public static void main(String[] args) { // try (and fail) to create an ArrayList of int's ArrayList<int> list = new ArrayList<int>(); // will not compile! list.add(1); list.add(2); list.add(3); System.out.println(list); } }
Fixed with Wrapper Class and Autoboxing:
import java.util.*; class MyCode { public static void main(String[] args) { // Create an ArrayList of Integers (Wrapper Class for ints) ArrayList<Integer> list = new ArrayList<Integer>(); // works! list.add(1); // Autoboxes 1 to Wrapper Class instance: new Integer(1) list.add(2); list.add(3); System.out.println(list); } }
import java.util.*; class MyCode { public static void main(String[] args) { System.out.println("Demo showing the hazards of autoboxing."); ArrayList<Integer> list = new ArrayList<Integer>(); list.add(1234); list.add(1234); System.out.println("Original list: " + list); System.out.println("\nAll the following should be true:"); System.out.println(list.get(0) == 1234); // works System.out.println(list.get(1) == 1234); // works System.out.println(list.get(0) == list.get(1)); // fails! System.out.println("\nNow the following WILL be true:"); int i0 = list.get(0); int i1 = list.get(1); System.out.println(i0 == 1234); // works System.out.println(i1 == 1234); // works System.out.println(i0 == i1); // also works! System.out.println(); System.out.println("Moral: only use autoboxing when necessary, and use"); System.out.println("real primitives (ints, doubles, etc) for all arithmetic!"); } }
class MyCode {
public static void main(String[] args) {
String[] array = { "Steelers", "Penguins", "Pirates" };
System.out.println("Traversing array using an enhanced for loop:");
for (String s : array)
System.out.println(s);
}
}
import java.util.*;
class MyCode {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("Larry");
list.add("Moe");
list.add("Larry");
list.add("Curly");
System.out.println("Traversing list using an enhanced for loop:");
for (String s : list)
System.out.println(s);
}
}
import java.util.*;
class MyCode {
public static void main(String[] args) {
HashSet<String> set = new HashSet<String>();
set.add("Larry");
set.add("Moe");
set.add("Larry"); // duplicate is effectively ignored
set.add("Curly");
System.out.println("Traversing set using an enhanced for loop:");
for (String s : set)
System.out.println(s);
}
}
import java.util.*; class MyCode { public static void main(String[] args) { HashMap<String, String> map = new HashMap<String, String>(); map.put("Paris", "France"); map.put("Ankara", "Turkey"); map.put("Doha", "Qatar"); System.out.println("Traversing map KEYS using an enhanced for loop:"); for (String key : map.keySet()) System.out.println(key); System.out.println(); System.out.println("Traversing map KEY-VALUE PAIRS using an enhanced for loop:"); for (String key : map.keySet()) System.out.println(key + ", " + map.get(key)); } }
import java.util.*; class MyCode { public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>(); list.add("Douglas Adams"); String name = list.get(0); System.out.println(name); HashSet<String> set = new HashSet<String>(); set.add("Blaise Pascal"); boolean blaiseIsThere = set.contains("Blaise Pascal"); System.out.println(blaiseIsThere); HashMap<String, String> map = new HashMap<String, String>(); map.put("Denver", "sunny"); String weatherInDenver = map.get("Denver"); System.out.println(weatherInDenver); } }
Unchecked (Old Style)
import java.util.*; @SuppressWarnings("unchecked") class MyCode { public static void main(String[] args) { ArrayList list = new ArrayList(); list.add("Douglas Adams"); String name = (String) list.get(0); System.out.println(name); HashSet set = new HashSet(); set.add("Blaise Pascal"); boolean blaiseIsThere = set.contains("Blaise Pascal"); System.out.println(blaiseIsThere); HashMap map = new HashMap(); map.put("Denver", "sunny"); String weatherInDenver = (String) map.get("Denver"); System.out.println(weatherInDenver); } }
import java.util.*; class MyCode { public static void main(String[] args) { System.out.println("Demo showing efficiency of the JCF."); int n = 25000; System.out.print("Add " + n + " elements using arrays: "); long time0 = System.currentTimeMillis(); int[] array = new int[0]; for (int i=0; i<n; i++) array = add(array, i); assert(array.length == n); long time1 = System.currentTimeMillis(); int elapsedTime = (int) (time1 - time0); System.out.println(elapsedTime + " ms"); System.out.print("Add " + n + " elements using an ArrayList: "); time0 = System.currentTimeMillis(); ArrayList<Integer> list = new ArrayList<Integer>(); for (int i=0; i<n; i++) list.add(i); assert(list.size() == n); time1 = System.currentTimeMillis(); elapsedTime = (int) (time1 - time0); System.out.println(elapsedTime + " ms"); } // From class notes on 1d-arrays: public static int[] add(int[] a, int newValue) { int[] result = new int[a.length+1]; for (int i=0; i<a.length; i++) result[i] = a[i]; result[a.length] = newValue; return result; } }
import java.util.*; class MyCode { public static void main(String[] args) { System.out.println("Enter a list of words (sentinel = 'end'):"); Scanner scanner = new Scanner(System.in); String next; // ArrayList<String> is like a variable-sized String[] ArrayList<String> list = new ArrayList<String>(); while (! (next = scanner.next()).equals("end")) list.add(next); System.out.println(); System.out.println("Here are all the words you entered:"); System.out.println(list); System.out.println(); System.out.println("Here is every-other-word:"); for (int i=0; i<list.size(); i+=2) System.out.print(list.get(i) + " "); System.out.println("\n"); System.out.println("Here they are in reverse:"); Collections.reverse(list); System.out.println(list); System.out.println(); System.out.println("And here they are sorted:"); Collections.sort(list); System.out.println(list); System.out.println(); } }
import java.util.*; class MyCode { public static void main(String[] args) { System.out.println("Enter a list of words with some DUPLICATES (sentinel = 'end'):"); Scanner scanner = new Scanner(System.in); String next; // HashSets are like Lists but WITHOUT DUPLICATES HashSet<String> set = new HashSet<String>(); while (! (next = scanner.next()).equals("end")) set.add(next); System.out.println(); System.out.println("Here are all the UNIQUE words you entered:"); System.out.println(set); System.out.println(); System.out.println("Now enter some words to see if they are in the first list:"); String key; while (! (key = scanner.next()).equals("end")) { if (set.contains(key)) System.out.println(key + " is in the original set."); else System.out.println(key + " is NOT in the original set"); } } }
import java.util.*; class MyCode { public static void main(String[] args) { System.out.println("Enter key-value PAIRS of words (sentinel = 'end'):"); Scanner scanner = new Scanner(System.in); String nextKey, nextValue; // A HashMap maps keys to values HashMap<String, String> map = new HashMap<String, String>(); while (! (nextKey = scanner.next()).equals("end")) { nextValue = scanner.next(); map.put(nextKey, nextValue); } System.out.println(); System.out.println("Here is the map you entered:"); System.out.println(map); System.out.println(); System.out.println("Now enter some words to see what they map to:"); String key; while (! (key = scanner.next()).equals("end")) { String value = map.get(key); if (value == null) System.out.println(key + " is NOT in the original map"); else System.out.println(key + " maps to " + value); } } }
carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem