Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 M255 Object-oriented programming with Java Prepared By: Prof. Dr. Shehab Gamalel-Din Unit 10 Collections: Sets & Maps.

Similar presentations


Presentation on theme: "1 M255 Object-oriented programming with Java Prepared By: Prof. Dr. Shehab Gamalel-Din Unit 10 Collections: Sets & Maps."— Presentation transcript:

1 1 M255 Object-oriented programming with Java Prepared By: Prof. Dr. Shehab Gamalel-Din Unit 10 Collections: Sets & Maps

2 2 Objectives Collection framework that is found in java.util.*; Set interface with its HashSet, and TreeSet to implement Set interface; Map interface is used to insert key_value pairs, and its implementation classes: HashMap and TreeMap; Collections methods; Map methods. This unit covers:

3 3 1. Collections A collection is a structure which enables multiple items to be bundled as a single unit and are dealt with collectively. A collection can be treated as a single object and its contents can be processed all together by stepping through the collection doing the same thing to each item as we go. The collection of items in java could be represented as: set, list, queue, and map where they differ from each other in terms of: – Size: fixed or dynamic – Ordering: are contents in particular order or not? – Homogeneity: are all elements of the same type? – Indexing: are elements in the collections given a label, index, key, or address of some sort to be located? – Duplicates: are duplicates allowed or not? contain only a list of methods without any actual implementation, in effect they are abstract methods. 1.Interface Type: Set, or List, Queue, or Map. 2.Implementing class: since it is an interface there are other classes that implement it 3.Element data type that will be held in this collection In declaring a collection of items, you need to decide: Array is a collection of components, but is not considered to be part of the Collections Framework. Arrays do not implement any of collection interfaces.

4 4 1.1 The Collection Interface Hierarchy The java Collections Framework provides different interfaces to collections such as Set, List, Queue, and Map. So Collections the super-interface and Set, List, Queue are sub- interfaces. TreeMap and TreeSet are sorted collections

5 5 1.2 Collection Sub-Interface Methods The collection sub-interfaces all have common methods in which any of Set, List, and Queue can use

6 6 2. The Set Collection A Set is an unordered collection which has no indexing, that contains no duplicates and which has a dynamic size (i.e. it can grow and shrink as elements are added and removed). Set is an interface that has more than one class that implements the Set such as: – HashSet class: general purpose class – TreeSet class: generates a sorted set The general structure of declaring a set is: Set set_name; E.g., Set herbSet; // herbSet is a set to hold strings To create an instance of a particular set: Setname = new Concstructor_implememtig_Class (); E.g., herbSet = new HashSet (); Note: The variable herbSet is declared of an interface type (Set) not the implementing class (HashSet), this way is more flexible and easier to maintain. This interface (Set) and its implanting class (HashSet) are found on: java.util.*; 1.Interface Type: Set, or List, Queue, or Map. 2.Element data type that will be held in this collection 3.Implementing class: since it is an interface there are other classes that implement it In declaring a collection of items, you need to decide: Interface Type Implementin g class Element data type

7 7 2.1 Operations on Sets SortedSet sub-interface in addition to above methods has an extra two methods: – first(): returns the first element in a sorted set. – last(): returns the last element in a sorted set.

8 8 Examples 1. Declare and create a set called herbSet that holds String elements.Set herbSet = new HashSet (); 2. Print the size of the herbSet System.out.println( herbSet.size() ); // size =0 3. Write a code to test if herbSet is empty or not boolean temp = herbSet.isEmpty(); // true if (temp) System.out.println(“Set is empty”); else System.out.println(“Set is not empty”); 4. Add the following elements into herbSet: “Parsley”, “Sage”, “Rosemary” herbSet.add(“Parsley”); herbSet.add(“Sage”); herbSet.add(“Rosemary”); 5. Print the size of the set System.out.println(herbSet.size()); // size is 3 6. Test if “Sage” is an element of herbSet. If (herbSet.contains(“Sage”) ) System.out.println(“Sage is an element of herbSet”); else System.out.println(“Sage is not an element of herbSet”); 7. Add another two elements: “Parsely”, and “Camomile”. Then test the size of herbSet herbSet.add(“Parsley”); herbSet.add(“Camomile”); System.out.prinltn(herbSet.size()); The result is 4 elements because “Parsley” will not be added again since it already exists. Duplication is not allowed. 8. Make an array herbs of HerbSet. Object[] herbs = herbSet.toArray();

9 9 Examples 9. Delete element “Sage” from the herbSet. Then delete element ”Mint” boolean del1, del2; del1 = herbSet.remove(“Sage”); del2 = herbSet.remove(“Mint”); Mint is not an element in herbSet, so nothing will happen, and del2 will be false. Note: you can also write the add and remove statements directly: herbSet.remove(“Sage”); herbSet.add(“Mint”); 10. Print herbSet elements. for(int i=0; i< herbs.length; i++) //using array System.out.println(herbs[i]); OR: for(String x: herbSet) //for each statement System.out.prinltn(x); OR: System.out.println(herbSet); Since the collection is treated as one unit, it could be printed as a whole.

10 10 2.2 Primitive data types and collections To declare a Set or any other collection interface, primitive data types: int, double, char are not allowed to be used as unless they are wrapped using the Wrapper classes. The wrapper class for int is Integer, and the wrapper class for double is Double, and so on. You declare and create a Set of primitive data types as follows: Set num = new HashSet (); // integer set Set numd = new HashSet (); // double set primitive values cannot be inserted into any collection unless they are wrapped. Integer wrappedNum = new Integer(7); Also arithmetic operation are not allowed on a wrapped object until it is unwrapped, then do calculation, and then do the wrapping again. int unwrappedNum = wrappedNum.intValue( ); This process of wrapping, and un-wrapping for primitive values is done automatically in Java and is known as autoboxing process. We do not have to worry about the distinction Integer, Set myNumbers = new HashSet ( ); myNumbers.add(7);

11 11 Exercises 1. Write a Java code to do the followings: Declare and create an integer Set called set1. Insert the following values: 12, 9, 8, 4 Find average of set1 and print it Print elements of set1. set set1 = new HashSet (); set1.add(12); set1.add(9); set1.add(8); set1.add(4); int sum =0; for(Integer x : set1) sum = sum + x; System.out.println(“Average of set1 is “ + sum/set1.size()); for(Integer eachn : set1) System.out.println(eachn); 2. Create another integer Set set2. set set2 = new HashSet (); 3. Insert the following elements: 9, 8, 7, 5, 6 in set2 set2.add(9); set2.add(8); set2.add(7); set2.add(5); set2.add(6); 4. Write a method read() that takes a Set as argument, and fill set with elements entered by the user. public void read(Set setA) { String s = OUDialog.request(“Enter a number”); while (s != null) { setA.add(Integer.parseInt(s)); s = OUDialog.request(“Enter a number or press cancel to stop”); } }

12 12 Examples 5. Create and declare a set common which has the common elements between set1, and set2 (intersection). - you need to copy set1 in common - then find intersection using retainAll() set common = new HashSet (set1); common.retainAll(set2); // set 1  set 2 6. Create and declare a set union which has the union of the two sets set1 and set2. set union = new HashSet (set1); union.addAll(set2); // set1  set2 addAll() will add argument to receiver, if any element is duplicate, it will not be duplicated. 7. Create and declare difference set that holds the elements in set1 – set2. set difference = new HashSet (set1); difference.removeAll(set2); // set1 – set2 8. Write a method brint() that returns nothing and take Set as parameter, it prints the argument’s contents; then send this message to set1, set2, union, common, and difference. public void brint(Set setA) { for(Integer x : setA) System.out.print(x + “ “); System.out.println(); }

13 13 2.3. TreeSet – a set with order TreeSet is a class that implements the SortedSet interface of Set. If you want the set to be printed in Ascending Sort you need to create the set as TreeSet. Example: Set herbSet = new TreeSet (); herbSet.add(“Mint”); herbSet.add(“Camomile”); herbSet.add(“Sage”); If you print the herbSet now: System.out.println(“herbSet is: “ + herbSet); The result will be: herbSet is: [Camomile, Mint, Sage] printed in alphabetical order. Set implementation classes are: HashSet and TreeSet. However, you can not call last() and first() because they belong to SortedSet interface not to the Set. Print the first and last elements: In this case you need to define another object: SortedSet herbSetOrder = new TreeSet (herbSet); System.out.println("First herb is: " + herbSetOrder.first()); System.out.println("Last herb is: " + herbSetOrder.last()); Notes: if herbSet was declared to be of type Set, the last() and first() methods will not work. When adding a new element to the set using add(), it will check first if element is not found, it could be added, otherwise false will return and nothing happen.

14 14 3. Map – a collection with keys and values A map is an unordered collection of key-value pairs. Duplicate keys are not allowed as they are used to look up their associated values. A map has dynamic size. A key is simply some information that can be used to uniquely identify any object from a given collection, and hence used to look up the associated object. – The key should not be duplicated, – It is used to distinguish a whole entry For example an index of a book: Word Page number Map 42 Set 35 Array 19 Exercises: Q1. For each of the following, tell whether or not it can work as an acceptable key. If you think it would, suggest what value the key might be associated with: (a) The workers’ number for employees in a company: Yes. The corresponding value might be an employment record or personnel file, etc. (b) The name of your Open University tutor amongst the body of OU tutors. This choice of key might be dangerous for some courses. There are some OU tutors with the same name. A likely value would be a tutorial group. (c) Your Open University student identifier amongst all OU students. This is a unique key. The value might be marks for a given course, or the student record, etc. Key Value

15 15 An Example Pirate Jake’s name is not unique in this table, and so names cannot act as unique keys for extension numbers. By changing the type of the values to be stored in the map from individual extension numbers into sets of extension numbers. now each key would have a single value, which was a set of numbers, even though the majority of sets includes one number. Thus, Pirate Jake could still have two telephone numbers while everyone else has a single number. Telephone Directory Set

16 16 3.1 Declare and create a Map instance Map interface has the following classes that implements Map: – HashMap: general purpose class – TreeMap: ordered map In order to declare and create a Map instance you need to determine: – Type of key, then type of values – Decide which implementing class you will use. General format to declare and create a Map instance is: Map Map_name = new implementing_class (); Example: Map accounts = new HashMap ();

17 17 3.2 The Map’s Interface Methods The put() method, adds a new pair key-value in the map only if the key does not exist. But if the key already exists, then the new key-value will overwrite the previous one. No duplicates are allowed.

18 18 Examples 1. Declare and create an ageMap that has String key representing person_name, and Integer to represent its age (value). Map ageMap = new HashMap (); 2. Insert following key-value pair in ageMap: Sami 33, Ali 38, Ahamd 25, Bader 27 ageMap.put("Sami", 33); ageMap.put("Ali", 38); ageMap.put("Ahmad", 25); ageMap.put("Bader", 27); 3. Print the ageMap. System.out.prinltn(ageMap); OR for(String x : ageMap.keySet()) { System.out.println(x + "- - >" + ageMap.get(x)); } 4. Write a method average to print the average of ages in ageMap public void average(Map ageMap) { int sum = 0; Set keys = new HashSet (); Integer value; Keys = ageMap.keySet(); for(String x : keys) { value = ageMap.get(x); sum = sum + value; } System.out.println("Average ages = " + sum/ageMap.size()); }

19 19 Examples 5. Create and declare another ageMap2 that has the same key-value pair but sorted, then print it. Map ageMap2 = new TreeMap (ageMap); System.out.println(ageMap2); 6. Print the value associated with the key "Bader". System.out.println(ageMap.get("Bader"); 7. Add another key-value: Ali 25, and then print the map to see what happened ageMap.put("Ali", 25); System.out.println(ageMap); 8. Print the size of the ageMap System.out.println(ageMap.size()); 9. Remove the entry whose key is: Sami. Integer v = ageMap.remove("Sami"); System.out.println(v); 10. Test if ageMap contains an entry with key: Ahmad. System.out.println( ageMap.containsKey("Ahmad")); 11. Test if ageMap contains value 25 System.out.println( ageMap.containsValue(25)); 12. Declare a Map to store person and their hobbies assuming that a person may have more than one hobbies, e.g., Ali gardening, music Sami walking, reading, sailing Map > client = new HashMap >(); Set hobbies = new HashSet (); // declare a set to hold hobbies of one person hobbies.add("gardening"); hobbies.add("music"); client.put("Ali", hobbies);

20 20 SAQs Q1. (a) What is the main difference between maps and sets? (b) A collection is needed in an Open University system to store student identifiers with the current total of OU credits each student has studied. Would a map be an appropriate collection interface for this task? Give a reason for your answer. Q2. Which of the following statements are true and which are false? If you think a statement is false, give a reason. (a) The message put( ) always enters a new entry in a map. (b) Each entry in a map has a key and one or more values. (c) Duplicate keys are allowed in a map. (d) The message get( ) returns the value of some entry within a map which has a key that matches the message’s argument. Q3. Name any three methods in the Set interface and any three methods in the Map interface. At least two should be common to both interfaces. Q4. We have not yet said anything about the interfaces List and Queue, but you can be sure that any abstract methods declared in Collection must be inherited by the interfaces Set, List and Queue. Why can we be sure of this? Q5. Do all of the classes in the Collections Framework implement the Collection interface? Q6. Name a method in SortedSet that is not in Set. Q7. Assume the following statement: Map accounts = new HashMap (); (a) In the above statement, why is the declared type of the variable – Map – different from the implementing class HashMap? (b) In the above statement, what is the purpose of the text in the angle brackets? Q8. Assume you have a Set of integer named numSet. The following code: for(Integer eachNum : numSet) Total = total + eachNum; (a) Why has the foreach statement’s local variable eachNum been declared of the Integer class, when the code prior to the foreach statement has been adding values of the primitive type int to the set? (b) In a HashSet, can we predict with certainty in what order the elements will be iterated over?

21 21 Finally Also read the summary and the glossary, and to solve all the exercises, SAQ, and activities. Do all activities Carefully study the Dating Agency example given in Section 4 page 37


Download ppt "1 M255 Object-oriented programming with Java Prepared By: Prof. Dr. Shehab Gamalel-Din Unit 10 Collections: Sets & Maps."

Similar presentations


Ads by Google