Download presentation
Presentation is loading. Please wait.
Published byMildred Johnston Modified over 9 years ago
2
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. AP Exam Alert
3
Collections A collection is a group of objects.
4
Unordered Collections An unordered collection stores elements without order.
5
Bags A bag is an unordered collection that can have duplicate elements.
6
Sets A set is an unordered collection without any duplicate elements.
7
Java Collection Hierarchy Collection Interface List Interface Set Interface ArrayList class LinkedList class HashSet class TreeSet class
8
// Java3701.java // This program reviews the two implementations, which are the // and classes, with the 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(); }
9
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 Select the Parameters tab Uncheck the Show Warning box Click OK
10
// Java3702.java // This program demonstrates that objects do not contain // duplicate elements like objects. It also demonstrates that // 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(); }
11
Constructing a Set Object HashSet hSet = new HashSet(); TreeSet tSet = new TreeSet(); or you can use Set hSet = new HashSet(); Set tSet = new TreeSet();
12
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.
13
// Java3703.java // This program demonstrates how to use an object, with the method, to // access every element in a object. It also demonstrates the 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"); }
14
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.
15
Iterator Method next System.out.print(hAccess.next()+" "); Method next moves the iterator to the next element, and then returns it.
16
Set Method size for (int k = 0; k < hSet.size(); k++) Method size returns the number of elements in the Set object.
17
// Java3704.java // This program demonstrates how to create a conditional loop with the // method of the 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"); }
18
Iterator Method hasNext while (iter.hasNext()) Method hasNext returns true if elements remain in the Collection object and returns false otherwise.
19
// Java3705.java This program demonstrates the method of the 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 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 method."); System.out.println(hSet); System.out.println(tSet); System.out.println(); }
20
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 the element specified in the parameter, if it exists in the Set object.
21
// Java3706.java // This program demonstrates the method of the interface, // which is not the same as the 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 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 method."); System.out.println(hSet); System.out.println(tSet); System.out.println(); }
22
// Java3707.java // This program demonstrates the method of the 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(); }
23
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.
25
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
26
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 A B
27
Why you did not learn Set Theory in your Math classes 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.
28
// Java3708.java // This program demonstrates an implementation of an method. import java.util.*; public class Java3708 { public static void main (String args[]) { System.out.println("\nJAVA3708.JAVA\n"); Random rnd = new Random(12345); Set s1 = new HashSet(); for (int k = 1; k <= 5; k++) { Integer obj = new Integer(rnd.nextInt(10)); s1.add(obj); } System.out.println("s1 Elements: " + s1); Set s2 = new HashSet(); for (int k = 1; k <= 5; k++) { Integer obj = new Integer(rnd.nextInt(10)); s2.add(obj); } System.out.println("s2 Elements: " + s2); Set s3 = intersection(s1,s2); System.out.println("\nIntersection of s1 and s2: " + s3); System.out.println(); } public static Set intersection( Set s1, Set s2) { Set temp = new HashSet(); Iterator iter = s1.iterator(); while (iter.hasNext()) { Integer number = (Integer) iter.next(); if (s2.contains(number)) temp.add(number); } return temp; } 8 1 2 0 5 4 9
29
// Java3709.java // This program demonstrates an implementation of a method. import java.util.*; public class Java3709 { public static void main (String args[]) { System.out.println("\nJAVA3709.JAVA\n"); Random rnd = new Random(12345); Set s1 = new HashSet(); for (int k = 1; k <= 5; k++) { Integer obj = new Integer(rnd.nextInt(10)); s1.add(obj); } System.out.println("s1 Elements: " + s1); Set s2 = new HashSet(); for (int k = 1; k <= 5; k++) { Integer obj = new Integer(rnd.nextInt(10)); s2.add(obj); } System.out.println("s2 Elements: " + s2); Set s3 = union(s1,s2); System.out.println("\nUnion of s1 and s2: " + s3); System.out.println(); } public static Set union(Set s1, Set s2) { Set temp = new HashSet(); Iterator iter1 = s1.iterator(); Iterator iter2 = s2.iterator(); while (iter1.hasNext()) { Object number1 = iter1.next(); temp.add(number1); } while (iter2.hasNext()) { Object number2 = iter2.next(); temp.add(number2); } return temp; } 8 1 2 0 5 4 9
30
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] 10 40 70 20 50 80 30 60 90
31
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 A B
32
// Java3710.java // This program demonstrates an implementation of a method. import java.util.*; public class Java3709 { public static void main (String args[]) { System.out.println("\nJAVA3709.JAVA\n"); Random rnd = new Random(12345); Set s1 = new HashSet(); for (int k = 1; k <= 5; k++) { Integer obj = new Integer(rnd.nextInt(10)); s1.add(obj); } System.out.println("s1 Elements: " + s1); Set s2 = new HashSet(); for (int k = 1; k <= 5; k++) { Integer obj = new Integer(rnd.nextInt(10)); s2.add(obj); } System.out.println("s2 Elements: " + s2); Set s3 = difference(s1,s2); Set s4 = difference(s2,s1); System.out.println("\nDifference of s1 and s2: " + s3); System.out.println("Difference of s2 and s1: " + s4); System.out.println();} public static Set difference( Set s1, Set s2) { Set temp = new HashSet(); Iterator iter = s1.iterator(); while (iter.hasNext()) { Integer number = (Integer) iter.next(); if (!s2.contains(number)) temp.add(number); } return temp; } 8 1 2 0 5 4 9
34
Math Example x-valuey = x + 2y - valuex-valuey = x 2 - 3y-value 1y = 1 + 231y = 1 - 3-2 2y = 2 + 242y = 4 - 31 3y = 3 + 253y = 9 - 36 4y = 4 + 264y = 16 - 313 5y = 5 + 275y = 25 - 322 6y = 6 + 286y = 36 - 333 7y = 7 + 297y = 49 - 346 8y = 8 + 2108y = 64 - 361 9y = 9 + 2119y = 81 - 378 In the example below call the x-value the key and the y-value the value or the target. For the y = x + 2 function we can say that 1 maps to 3 & 2 maps to 4. For the y = x 2 - 2 function we can say that 1 maps to -2 & 2 maps to 1.
35
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. CountryCapitalCountryCapital Belgium Brussels France Paris Germany Berlin Austria Vienna Netherlands AmsterdamLuxembourg ColumbiaBogotá Spain Madrid Italy RomePoland Warsaw
36
// Java3711.java // This program introduces the and classes with the 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(); }
37
Constructing a Map Object HashMap hMap = new HashMap(); TreeMap tMap = new TreeMap(); or you can use Map hMap = new HashMap(); Map tMap = new TreeMap();
38
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.
39
// 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(); }
40
// Java3713.java // This program demonstrates that keys in a object are not sorted. // Keys in a 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(); }
42
// Java3714.java // This program demonstrates that the 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(); }
43
// Java3715.java // This program demonstrates that the 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); }
44
Map Method put The 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.
45
// Java3716.java // This program demonstrates the 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(); }
46
// Java3717.java // This program demonstrates the 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(); }
47
// Java3718.java // This program uses a user-defined 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; }
48
// Java3719.java // This program demonstrates how to use a map object as a dictionary. // It also demonstrates the use of the method, which returns a // object of available keys in a 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; }
49
// 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"; }
52
// Java3721.java // This program demonstrates using the element type // with a object. import java.util.*; public class Java3721 { public static void main (String args[]) { System.out.println("\nJAVA3721.JAVA\n"); Set numbers = new HashSet (); for (int k = 1000; k <= 5000; k+=1000) numbers.add(k); Iterator iter = numbers.iterator(); int sum = 0; while (iter.hasNext()) sum += iter.next(); System.out.println("Sum: " + sum); System.out.println(); }
53
// Java3722.java // This program demonstrates that it is not necessary to use the element type // declaration everywhere. It is only required at the point where it is not // clear what type object is being used. import java.util.*; public class Java3722 { public static void main (String args[]) { System.out.println("\nJAVA3722.JAVA\n"); Set numbers = new HashSet(); for (int k = 1000; k <= 5000; k+=1000) numbers.add(k); Iterator iter = numbers.iterator(); int sum = 0; while (iter.hasNext()) sum += iter.next(); System.out.println("Sum: " + sum); System.out.println(); }
54
// Java3723.java This program demonstrates an implementation of an method. // This is the previous Java3708.java program, but this time it uses Java 5.0 features of autoboxing and // generics. In this example the element type is used all over the program. import java.util.*; public class Java3723 { public static void main (String args[]) { System.out.println("\nJAVA3723.JAVA\n"); Random rnd = new Random(12345); Set s1 = new HashSet (); for (int k = 1; k <= 5; k++) { int rndInt = rnd.nextInt(10); s1.add(rndInt); } System.out.println("s1 Elements: " + s1); Set s2 = new HashSet (); for (int k = 1; k <= 5; k++) { int rndInt = rnd.nextInt(10); s2.add(rndInt); } System.out.println("s2 Elements: " + s2); Set s3 = intersection(s1,s2); System.out.println("\nIntersection of s1 and s2: " + s3); System.out.println(); } public static Set intersection(Set s1, Set s2) { Set temp = new HashSet (); Iterator iter = s1.iterator(); while (iter.hasNext()) { int number = iter.next(); if (s2.contains(number)) temp.add(number); } return temp; }
55
// Java3724.java // Program Java3724.java repeats program Java3723.java, but the // element type is only used where it is necessary. import java.util.*; public class Java3724 { public static void main (String args[]) { System.out.println("\nJAVA3724.JAVA\n"); Random rnd = new Random(12345); Set s1 = new HashSet(); for (int k = 1; k <= 5; k++) { int rndInt = rnd.nextInt(10); s1.add(rndInt); } System.out.println("s1 Elements: " + s1); Set s2 = new HashSet(); for (int k = 1; k <= 5; k++) { int rndInt = rnd.nextInt(10); s2.add(rndInt); } System.out.println("s2 Elements: " + s2); Set s3 = intersection(s1,s2); System.out.println("\nIntersection of s1 and s2: " + s3); System.out.println(); } public static Set intersection(Set s1, Set s2) { Set temp = new HashSet(); Iterator iter = s1.iterator(); while (iter.hasNext()) { int number = iter.next(); if (s2.contains(number)) temp.add(number); } return temp; }
56
// Java3725.java // This program presents generics with maps. The (String) class casting is not necessary now. import java.util.*; public class Java3725 { public static void main (String args[]) { System.out.println("\nJava3725.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(); }
57
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 map.get(word); else return "not in dictionary"; }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.