580 likes | 669 Views
Exposure Java 2006. Chapter 37 Slides. Sets & Maps. PowerPoint Presentation created by: Mr. John L. M. Schram. From Materials Created by Mr. Leon Schram. AP Exam Alert.
E N D
Exposure Java 2006 Chapter 37 Slides Sets & Maps PowerPoint Presentation created by: Mr. John L. M. Schram From Materials Created by Mr. Leon Schram
AP Exam Alert The HashSet, TreeSet, HashMap and TreeMap are four classes that are part of the Java AB subset, which may be tested on the AP Computer Science Examination.
Collections A collection is a group of objects.
Unordered Collections An unordered collection stores elements without order.
Bags A bag is an unordered collection that can have duplicate elements.
Sets A set is an unordered collection without any duplicate elements.
Java Collection Hierarchy Collection Interface List Interface Set Interface ArrayList class LinkedList class HashSet class TreeSet class
// Java3701.java // This program reviews the two <Set> implementations, which are the // <TreeSet> and <HashSet> classes, with the <add> method. import java.util.*; public class Java3701 { public static void main (String args[]) { System.out.println("\nJAVA3701.JAVA\n"); int[] numbers = {10,90,20,80,30,70,40,60,50}; Set hSet = new HashSet(); Set tSet = new TreeSet(); for (int k = 0; k < numbers.length; k++) { hSet.add(new Integer(numbers[k])); tSet.add(new Integer(numbers[k])); } System.out.println(hSet); System.out.println(tSet); System.out.println(); } }
Java Warning Messages • Java warning messages can be annoying and cause concern when there is nothing wrong. • This is true for the program examples in this chapter. • It is easy to turn the warning messages off in JCreator with the following steps: • Click Configure • Click Options • Click JDK Tools • Select Compiler in the pulldown tool type window • Highlight <Default> • Select the Parameters tab • Uncheck the Show Warning box • Click OK • Click OK
// Java3702.java // This program demonstrates that <Set> objects do not contain // duplicate elements like <List> objects. It also demonstrates that // <TreeSet> objects store elements in ascending order. import java.util.*; public class Java3702 { public static void main (String args[]) { System.out.println("\nJAVA3702.JAVA\n"); int[] numbers = {23,43,49,61,23,50,49,18,75,18}; List list = new ArrayList(); Set hSet = new HashSet(); Set tSet = new TreeSet(); for (int k = 0; k < numbers.length; k++) { list.add(new Integer(numbers[k])); hSet.add(new Integer(numbers[k])); tSet.add(new Integer(numbers[k])); } System.out.println(list); System.out.println(hSet); System.out.println(tSet); System.out.println(); } }
Constructing a Set Object HashSet hSet = new HashSet(); TreeSet tSet = new TreeSet(); or you can use Set hSet = new HashSet(); Set tSet = new TreeSet();
Set Method add hSet.add(new Integer(1000)); tSet.add(new Integer(2000)); Method add stores a new value in a Set object, provided the element is not already stored in the Set object.
// Java3703.java // This program demonstrates how to use an <Iterator> object, with the <next> method, to // access every element in a <Set> object. It also demonstrates the <size> method. import java.util.*; public class Java3703 { public static void main (String args[]) { System.out.println("\nJAVA3703.JAVA\n"); Set hSet = new HashSet(); Set tSet = new TreeSet(); for (int k = 10; k < 100; k+= 10) { hSet.add(new Integer(k)); tSet.add(new Integer(k)); } Iterator hAccess = hSet.iterator(); for (int k = 0; k < hSet.size(); k++) System.out.print(hAccess.next() + " "); System.out.println("\n\n"); Iterator tAccess = tSet.iterator(); for (int k = 0; k < hSet.size(); k++) System.out.print(tAccess.next() + " "); System.out.println("\n\n"); } }
Constructing an Iterator Object Iterator hAccess = hSet.iterator(); The iterator method of a Collection class object (ArrayList, LinkedList, HashSet and TreeSet) instantiates an object of the Iterator class, in this case hAccess.
Iterator Method next System.out.print(hAccess.next()+" "); Method next moves the iterator to the next element, and then returns it.
Set Method size for (int k = 0; k < hSet.size(); k++) Method size returns the number ofelements in the Set object.
// Java3704.java // This program demonstrates how to create a conditional loop with the // <hasNext> method of the <Iterator> class. import java.util.*; public class Java3704 { public static void main (String args[]) { System.out.println("\nJAVA3704.JAVA\n"); Set hSet = new HashSet(); Set tSet = new TreeSet(); for (int k = 10; k < 100; k+= 10) { hSet.add(new Integer(k)); tSet.add(new Integer(k)); } Iterator hAccess = hSet.iterator(); while (hAccess.hasNext()) System.out.print(hAccess.next() + " "); System.out.println("\n\n"); Iterator tAccess = tSet.iterator(); while (tAccess.hasNext()) System.out.print(tAccess.next() + " "); System.out.println("\n\n"); } }
Iterator Method hasNext while (iter.hasNext()) Method hasNext returns true if elements remain in the Collection object and returns false otherwise.
// Java3705.java This program demonstrates the <remove> method of the <Iterator> class. import java.util.*; public class Java3705 { public static void main (String args[]) { System.out.println("\nJAVA3705.JAVA\n"); Set hSet = new HashSet(); Set tSet = new TreeSet(); for (int k = 1; k <= 10; k++) { hSet.add(new Integer(k)); tSet.add(new Integer(k)); } System.out.println("Set elements before using the <remove> method."); System.out.println(hSet); System.out.println(tSet); Iterator hAccess = hSet.iterator(); Iterator tAccess = tSet.iterator(); for (int k = 1; k <= 10; k++) { hAccess.next(); tAccess.next(); if (k % 2 == 0) { hAccess.remove(); tAccess.remove(); } } System.out.println("\nSet elements after using the <remove> method."); System.out.println(hSet); System.out.println(tSet); System.out.println(); } }
2 remove Methods iter.remove(); Iterator method remove removes the current item referenced by the iterator. hSet.remove(new Integer(k)); Set method remove removes theelement specified in the parameter, if it exists in the Set object.
// Java3706.java // This program demonstrates the <remove> method of the <Set> interface, // which is not the same as the <Iterator> <remove> method>. import java.util.*; public class Java3706 { public static void main (String args[]) { System.out.println("\nJAVA3706.JAVA\n"); Set hSet = new HashSet(); Set tSet = new TreeSet(); for (int k = 1; k <= 10; k++) { hSet.add(new Integer(k)); tSet.add(new Integer(k)); } System.out.println("Set elements before using the <remove> method."); System.out.println(hSet); System.out.println(tSet); for (int k = 1; k <= 10; k++) { if (k % 2 == 0) { hSet.remove(new Integer(k)); tSet.remove(new Integer(k)); } } System.out.println("\nSet elements after using the <remove> method."); System.out.println(hSet); System.out.println(tSet); System.out.println(); } }
// Java3707.java // This program demonstrates the <contains> method of the <Set> interface, import java.util.*; public class Java3707 { public static void main (String args[]) { System.out.println("\nJAVA3707.JAVA\n"); Set tSet = new TreeSet(); Random rndInt = new Random(12345); for (int k = 1; k <= 100; k++) { tSet.add(new Integer(rndInt.nextInt(90) + 10)); } System.out.println("tSet Members"); for (int k = 10; k <= 99; k++) if (tSet.contains(new Integer(k))) System.out.print(k + " "); System.out.println(); } }
Set Method contains if (tSet.contains(new Integer(k))) Method contains returns true if the parameter value exists in the Set object and false otherwise.
Set Operations & Venn Diagrams Review
Venn Diagram #1 The Boolean Algebra logical and ( * ) can be demonstrated with Venn Diagrams, using intersection. A intersect B also A and B also A * B also AB
A B Venn Diagram #2 The Boolean Algebra logical or ( + ) can be demonstrated with Venn Diagrams, using union. A union B also A or B also A + B
Why you did not learn Set Theory in your Math classes 1960s After Sputnik, the United States adopted New Math in the classroom. After test scores went down the focus switched back to the "3 Rs" (Reading, Riting & Rithmetic). Unfortunately, they stopped New Math completely just as Technology courses were being introduced. 1990s
// Java3708.java // This program demonstrates an implementation of an <intersection> method. 8 1 2 0 5 4 9
// Java3709.java // This program demonstrates an implementation of a <union> method. 8 1 2 0 5 4 9
10 40 70 20 50 80 30 60 90 Set Difference A lesser-known set operation is set difference. In this operation all the elements of one set are returned that are not found in the second set. It is important to realize that difference can create two different results. The order is significant. Consider the following example. Set1 contains [10, 20, 30, 40, 50, 60] Set2 contains [40, 50, 60, 70, 80, 90] The difference of Set1 and Set2 or Set1 - Set2 = [10, 20, 30] The difference of Set2 and Set1 or Set2 - Set1 = [70, 80, 90]
A B Venn Diagram #3 Boolean Algebra logical subtraction ( - ) can be demonstrated with Venn Diagrams, using difference. A - B also A * ~B also A and not B also A not B
// Java3710.java // This program demonstrates an implementation of a <difference> method. 8 1 2 0 5 4 9
HashMaps & TreeMaps
Math Example In the example below call the x-value the keyand the y-value the valueor the target. For the y = x + 2 function we can say that 1 maps to 3 & 2 maps to 4. For the y = x2 - 2 function we can say that 1 maps to -2 & 2 maps to 1.
Geography Example Once again there is an association between the key (country) and its value or target (capital). In this example Belgium maps to Brussels, France maps to Paris, Germany maps to Berlin, etc.
// Java3711.java // This program introduces the <HashMap> and <TreeMap> classes with the <put> method. import java.util.*; public class Java3711 { public static void main (String args[]) { System.out.println("\nJAVA3711.JAVA\n"); Map hMap = new HashMap(); Map tMap = new TreeMap(); hMap.put("D","Dog"); hMap.put("B","Bear"); hMap.put("A","Aardvark"); hMap.put("C","Cat"); tMap.put("D","Dog"); tMap.put("B","Bear"); tMap.put("A","Aardvark"); tMap.put("C","Cat"); System.out.println(hMap); System.out.println(tMap); System.out.println(); } }
Constructing a Map Object HashMap hMap = new HashMap(); TreeMap tMap = new TreeMap(); or you can use Map hMap = new HashMap(); Map tMap = new TreeMap();
Map Method put hMap.put("C","Cat"); tMap.put("C","Cat"); Method put stores the first parameter - "C" - as the key and its second parameter - "Cat" - as the value or target.
// Java3712.java // This program investigates how data is sorted. It appears that the key (1, 2, 3, 4) is used. import java.util.*; public class Java3712 { public static void main (String args[]) { System.out.println("\nJAVA3712.JAVA\n"); Map hMap = new HashMap(); Map tMap = new TreeMap(); hMap.put("1","Dog"); hMap.put("2","Bear"); hMap.put("3","Aardvark"); hMap.put("4","Cat"); tMap.put("1","Dog"); tMap.put("2","Bear"); tMap.put("3","Aardvark"); tMap.put("4","Cat"); System.out.println(hMap); System.out.println(tMap); System.out.println(); } } NOTE: TreeMaps sort based on the key value. HashMaps do not sort at all. It may look like it was sorted by the target value, but that is just a coincidence.
// Java3713.java // This program demonstrates that keys in a <HashMap> object are not sorted. // Keys in a <TreeMap> object are sorted in ascending order. // The keys in each object map to the same target to focus on the key order. import java.util.*; public class Java3713 { public static void main (String args[]) { System.out.println("\nJAVA3713.JAVA\n"); Map hMap = new HashMap(); Map tMap = new TreeMap(); Random rnd = new Random(12345); System.out.println("Random Key Sequence"); for (int k = 1; k <= 20; k++) { Integer intObj = new Integer(rnd.nextInt(90) + 10); System.out.print(intObj + " "); hMap.put(intObj,"HashMap"); tMap.put(intObj,"TreeMap" ); } System.out.println("\n\n"); System.out.println(hMap); System.out.println("\n\n"); System.out.println(tMap); System.out.println(); } } Output on next slide
// Java3714.java // This program demonstrates that the <put> method can be used to replace existing // data in a map with the same key. import java.util.*; public class Java3714 { public static void main (String args[]) { System.out.println("\nJAVA3714.JAVA\n"); Map hMap = new HashMap(); Map tMap = new TreeMap(); hMap.put("D","Dog"); hMap.put("B","Bear"); hMap.put("A","Aardvark"); hMap.put("C","Cat"); tMap.put("D","Dog"); tMap.put("B","Bear"); tMap.put("A","Aardvark"); tMap.put("C","Cat"); System.out.println(hMap); System.out.println(tMap); System.out.println(); hMap.put("A","Anaconda"); tMap.put("A","Anaconda"); System.out.println(hMap); System.out.println(tMap); System.out.println(); } } NOTE: One key CANNOT be mapped to 2 different values.
// Java3715.java // This program demonstrates that the <put> method is a return method, which // returns the current value, prior to replacing a new value. import java.util.*; public class Java3715 { public static void main (String args[]) { System.out.println("\nJAVA3715.JAVA\n"); Map map = new TreeMap(); map.put("A","Aardvark"); map.put("B","Bear"); map.put("C","Cat"); map.put("D","Dog"); System.out.println(map.put("A","Andy")); System.out.println(map.put("B","Bonny")); System.out.println(map.put("C","Cliff")); System.out.println(map.put("D","Darlene")); System.out.println(); System.out.println(map); } }
Map Method putThe Rest of the Story System.out.println(map.put("A","Andy")); put is a return method, which returns the currently mapped value before replacing the mapping with the new value in its parameter .
// Java3716.java // This program demonstrates the <get> method, which returns // the object that is mapped to a specified key. import java.util.*; public class Java3716 { public static void main (String args[]) { System.out.println("\nJAVA3716.JAVA\n"); Map map = new TreeMap(); map.put(new Integer(15),"Dog"); map.put(new Integer(18),"Bear"); map.put(new Integer(21),"Aardvark"); map.put(new Integer(35),"Cat"); System.out.println(map); System.out.println(); for (int k = 1; k <= 50; k ++) { Integer key = new Integer(k); String target = (String) map.get(key); if (target != null) System.out.println(target); } System.out.println(); } }
// Java3717.java // This program demonstrates the <containsKey> method. // This makes the previous program more practical. import java.util.*; public class Java3717 { public static void main (String args[]) { System.out.println("\nJAVA3717.JAVA\n"); Map map = new TreeMap(); map.put(new Integer(15),"Dog"); map.put(new Integer(18),"Bear"); map.put(new Integer(21),"Aardvark"); map.put(new Integer(35),"Cat"); System.out.println(map); System.out.println(); for (int k = 1; k <= 50; k ++) { Integer key = new Integer(k); if (map.containsKey(key)) System.out.println(map.get(key)); } System.out.println(); } }
// Java3718.java // This program uses a user-defined <evenKeys> method, which returns a set of even-numbered map keys. import java.util.*; public class Java3718 { public static void main (String args[]) { System.out.println("\nJAVA3718.JAVA\n"); Map map = new TreeMap(); Random rnd = new Random(12345); for (int k = 1; k <= 10; k++) { Integer obj = new Integer(rnd.nextInt(1000)); map.put(new Integer(k),obj); } System.out.println(map); System.out.println(); System.out.println(evenKeys(map)); System.out.println(); } public static Object evenKeys(Map mapObj) { Set temp = new TreeSet(); for (int k = 1; k < mapObj.size(); k++) { Integer p = new Integer(k); Integer q = (Integer) mapObj.get(p); if (q.intValue() % 2 == 0) temp.add(p); } return temp; } }
// Java3719.java // This program demonstrates how to use a map object as a dictionary. // It also demonstrates the use of the <keySet> method, which returns a // <Set> object of available keys in a <Map> object. import java.util.*; public class Java3719 { public static void main (String args[]) { System.out.println("\nJAVA3719.JAVA\n"); String[] english = {"one","two","three","house","room","city","beach","bicycle"}; String[] dutch = {"een","twee","drie","huis","kamer","stad","strand","fiets"}; Translator englishDutch = new Translator(english,dutch); System.out.println(englishDutch); System.out.println(); } } class Translator { private Map map; public Translator(String[] key, String[] val) { map = new HashMap(); for (int k = 0; k < key.length; k++) if (!map.containsKey(key[k])) map.put(key[k],val[k]); } public String toString() { Set keys = new HashSet(); keys = map.keySet(); Iterator iter = keys.iterator(); String temp = ""; while (iter.hasNext()) { String key = (String) iter.next(); temp += key + " = " + map.get(key) + "\n"; } return temp; } }
// Java3720.java This program presents a more practical dictionary. It is now possible - with a limited vocabulary - // to translate English words interactively into Dutch words. The program concludes with the entry of "end". import java.util.*; public class Java3720 { public static void main (String args[]) { System.out.println("\nJava3720.java\n"); String[] english = {"one","two","three","house","room","city","beach","bicycle"}; String[] dutch = {"een","twee","drie","huis","kamer","stad","strand","fiets"}; Translator dictionary = new Translator(english,dutch); Scanner input = new Scanner(System.in); String englishWord = "begin"; while (!englishWord.equals("end")) { System.out.print("Enter an English word ===>> "); englishWord = input.nextLine(); System.out.println(); if (englishWord.equals("end")) System.out.println("Tot ziens"); else { String dutchWord = dictionary.getDutch(englishWord); System.out.println(englishWord + " in English equals " + dutchWord + " in Dutch"); } System.out.println(); } } } class Translator { private Map map; public Translator(String[] key, String[] val) { map = new HashMap(); for (int k = 0; k < key.length; k++) if (!map.containsKey(key[k])) map.put(key[k],val[k]); } public String getDutch(String word) { if (map.containsKey(word)) return (String) map.get(word); else return "not in dictionary"; } } Output on next slide