Java Collections
Java Collections
Collections in Java
LEVEL PRACTITIONER
Ashok Kumar Kanuparthi(g-Ashok3)/Renjith(t-renjith)/ Shanmu (105110) Trainer/Trainer/ Sr Architect 1.0, January 1st 2012
Icons Used
Hands on Exercise
Questions
Tools
Coding Standard s
Case Study
Demonstrati on
3
Worksho p
Objectives
After completing this session, you will be able to : Define Collections Describe usage of collections Describe the benefits of collections Understand the core Collection Interfaces Understand the implementations
Collection
Collections Framework
What is a collections framework? A collections framework is a unified architecture for representing and manipulating varieties of collections. Some collections allow duplicate elements and others do not. Can be used only to hold object type data (non primitive type). Some are ordered and others are unordered. The collection framework is available in the java.util package. Collection framework contains, A set of Interfaces. Concrete class implementations for the interfaces. The classes in turn has standard APIs for processing collections.
6
Easy to maintain
Easy to use.
Example: The collection sizes dynamically changes that is it gets shrunk or increased based on the elements stored.
Collection Interfaces
What are collection Interfaces? These are set of predefined java interfaces defined in java.util package which can be used for performing any logic related to collection of Objects. Example: Set, List, Map What are collection Implementations? These are predefined classed which implements one of the collection interfaces. The programmer uses these for processing collection of Objects. Example: ArrayList, HashMap.
A SortedMap is a Map that maintains its entries in ascending order, sorted based on the key
Problem 1 : You need to insert the above list of countries in the same order given above . What type of collection can be used ? Solution : Any ordered collection can be used. Example: List. Problem 2: Suppose you want to automatically sort the country names and store it in a collection ? What type of collection can be used ? Solution : A sorted collection like SortedSet can be used which automatically sorts and rearranges the value each time a new country is added to the list.
List
Vector
Array List
Hash Set
Tree Set
Vectors can hold duplicate values. This is thread safe. Array List can hold duplicate values. This is not thread safe. Can hold null values.
10
It allows duplicates
Set:
Cat Dog Bat Lion Bird null
11
Time To Reflect
Associates to reflect the following before proceeding. What is the collection type that can be used to hold duplicate values? What type of collection can be used for thread safe storage of elements with duplication? What type of collection can be used to store unique elements in a sorted order?
12
Collection Interface
The root interface in the collection hierarchy. JDK does not provide any direct implementations of this interface, it provides implementations of more specific sub-interfaces like Set and List etc. Contains methods which needs to implemented directly or indirectly by the sub classes. For more details on the methods specified in Collection interface refer, http://docs.oracle.com/javase/6/docs/api/java/util/Collection.html
13
List Interface
Used for storing the elements in a ordered way. Supports duplicate entries. Supports index based additions and retrieval of items. 1. Vector 2. ArrayList 3. LinkedList We will be covering only ArrayList implementation in details. For details on the other List Implementations refer LinkedList- http://docs.oracle.com/javase/6/docs/api/java/util/LinkedList.html. Vector - http://docs.oracle.com/javase/6/docs/api/java/util/Vector.html. 14
List implementations:
Array List
Implements List interface ArrayList can grow and shrink in size dynamically based on the elements stored hence can be considered as a variable array. Values are stored internally as an array hence random insert and retrieval of elements are allowed. Can be traversed using a foreach loop, iterators, or indexes. Initially gets created with an initial capacity , when this gets filled the list automatically grows. Can hold only object type data Cannot hold primitive type values. Supports duplicate entries. 15
16
17
18
Consider the code below what happens if the ArrayList API becomes deprecated ? How many changes should be done in the below code ?
All the red boxes are changes to be done. Lets see how to reduce it.
19
The solution is declaring the reference variable as the interface type rather than of the implementation type. Example all the list objects can be declared using List type.
Now change needs to be done in one place, where the object is created.
20
Adds the element lemon at position 1 moving orange to position 2. Adds elements one by one to the list. When set is used the item in the particular index will be replaced by the new item.
21
22
Create a class named ArrayListEx and develop the method as mentioned below and from the main method trigger this method and check the output.
Creates an array list object and adds the country names to it.
23
Add the following method in the ArrayListEx class and from the main method trigger this method and check the output.
Note: When a primitive is added to a collection it gets automatically converted to its equivalent wrapper object and loaded in the list. 24
Add the following method in the ArrayListEx class and from the main method trigger this method and check the output. The list returned by the previous problem statement should be passed as and input to this method.
25
Output
26
Set Interface
The Set interface is a collection that cannot contain duplicate elements. It permits a single element to be null. Set interface contains methods inherited from collection interface. Sorted Set interface is a set that maintains its elements in ascending order. Set Implementations: 1.HashSet 2.TreeSet
We will be covering only HashSet in detail in this session. For details on TreeSet visit http://docs.oracle.com/javase/1.4.2/docs/api/java/util/TreeSet.html
27
HashSet
Implements the Set interface hence doesnt support duplicate entries. Does not support random access or retrieval. Cannot predict the order in which the items get stored in the Set. Not Thread safe. Permits Null value(Only one).
28
29
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/HashSet.html
30
Elements can be added one by one using a add() method or an entire collection can be added using the addAll() method. Example: mySet.add(India);
Adds two elements into the set.
Note : If an entire set is added to another set , the duplicate elements will not get added.
31
32
Create a class SetEx, add the below method to the class. Invoke the method from a main method and test the method.
Always remember to declare the collection using the appropriate interface. In the example it is Set. 33
Add the below method to the SetEx class. Invoke the method from a main method and test the method.
Note: When a primitive is added to a collection it gets automatically converted to its equivalent wrapper object and loaded in the list. 34
Add the below method to the SetEx class. Invoke the method from a main method and test the method.
35
Output
36
Time To Reflect
Associates to reflect the following before proceeding. What method can be used to merge to two array lists ? What happens when a duplicate entry is tried to be added to a set ? What is the difference between add and set method in arraylist? How to add an element to a particular position in an array list?
37
38
Roses
Jewels
Chocolate
Here, the buyer is aware of what is inside the boxes ,since the box is labeled. This makes his job easier since he knows what he can put in and what he can take out from the box
39
Similar to the boxes how can one know what is the data type of the element stored in a collection?
40
What is Generics?
Generics is a feature allows the programmer to specify the data type to be stored in a collection or a class when developing the program.
Compile throws error if the data stored is different from the data type specified in the generic.
41
We will take the same box example but instead of jewels , chocolates and roses we will store java objects inside it. Consider a Box class,
public class Box { private Integer width; public void addWidth(Integer width) { this.width = width; } public Integer getWidth() { return width; } } Assume that I have to pass width as a Float (or) Double to the Box class. How can I achieve this? Generics is the solution.
42
43
44
We can declare collection to hold a specific data type elements using generics . Syntax: InterfaceName <Type> varName=new Implementation<Type>(); Example : Declares an array list for holding only integer values. List<Integer> myList=new ArrayList<Integer>();
45
1. Avoid unnecessary type casting : Using generics avoid the need of typecasting while retrieving the elements from the collection. Consider an ArrayList named countries ,elements can be retrieved from the List as shown below Without Generics With Generics
46
2. Minimize CastException during run time: For example assume a method returns a List of integers. The client is unaware about the type of data held by the collection and he may type cast it to some incompatible type and end up in CastException during runtime. In case of any invalid casting compiler will throw an error.. 3. Easy Maintenance & Readability : Looking at the code the developer can easily know the data type stored in the collection and thus helps him to process the collection easily.
47
48
Create a class named GenericEx and add the method given below. Generic Declaration
Try to add a Integer number to the List and see how the program behaves. 49
Generic Declaration
50
Output
51
Let us now see how to iterate through the collection and read elements one by one. The following are the ways to iterate through a collection
For loop Reads elements by specifying the index using the get() method Can be used only with List. Iterate over a list and gets the elements one by one until the complete list is covered Can be applied with both List and Set. Iterator provides methods to iterate through a collection. Can be applied with both List and Set. An iterator which support both forward and back ward iteration. Can be applied only with List.
For-each loop
Iterator
ListIterator
52
We will go through each of the iteration mechanism using a lend a hand example. We will reuse the classes we developed as part of the previous lend a hand, 1. ArrayListEx 2. SetEx
53
54
Create a class named ForLoopExMain with a main method. Add the following lines of code inside main method which can read the Country list from ArrayListEx and print it.
Note : Since Generics is not used, we can see that elements are explicitly casted to String type.
55
Add the following lines of code inside the main method to read the number list from ArrayListEx and calculate the sum of all the numbers in the list.
56
For-Each loop
1. For each loop was added as a part of java 5 2. Can be used to read elements from a collection or array 3. The advantage of for each is that we dont need to specify the index. It automatically iterates over the specified object and reads values one by one. Syntax :
for(datatype variableName : collectionName){ loop body } Example for(Object a : myList){ } Reads elements as objects one by one from the list MyList and System.out.println(a); assign to the variable a. Reads each element of the collection collectionName with the type datatype and assigns it to the variable variableName one by one.
57
58
59
Create a class named ForEachExMain with a main method Add the following lines of code to read the countries set from the SetEx class and iterate using for each loop and print it.
60
Add the following lines of code to the main method to find the sum of numbers in the number set read from the SetEx class
61
62
Iterator
What is an Iterator interface? This interface contains methods which is used for iterating & accessing all the elements of a collection in sequence. The List and Set collections can be iterated using iterators.
Iterator interface methods: Method boolean hasNext() Object next() void remove() Description true if there are more elements for the iterator. Returns the next object or elements. Removes the element that was returned by next from the collection. This method can be invoked only once per call to next .
63
64
It.next( )
It.next( )
It.next( )
The next element is retrieved everytime it.next() is executed. The hasnext() method is used for verifying the existence of element in the collection before firing the next().
65
66
67
Create an iterator to work on the set Invoke the hasNext() method to check whether the iterator contains elements to be read. Invoke the next() method to read each country from the Set.
Note :The Iterator is also declared with generics to avoid type casting. 68
69
ListIterator
An list iterator can be used by programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator's current position in the list. A ListIterator has no current element; its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next().
Note : In projects Iterator interface are used commonly. So we are not going to learn the implementation of ListIterator. Associates can refer to the oracle documentation for more details on ListIterator.
70
Time To Reflect
Associates to reflect the following before proceeding. How to make a collection accept only Integer objects? What are all the methods available to iterate through a Set? Can a ListIterator be used with a Set? Which iterator can be used to add elements to a list in between the iteration process? What may be the reason that for loop is not used to iterate through set?
71
Maps
Map stores Elements as key value pairs. Each key maps to one value stored in the map. The values can be accessed by passing the key. The key should be unique used to identify the value. The key and value can only be objects.
Key 1 2 3 4 5 Value India Australia England South Africa New Zealand
72
Map Interfaces
Map A Map is an object that maps keys to values
Hash Map
Hash Table
Tree Map
73
Collection
Cat Dog Bat Lion Bird Key C D B
Map
Value Cat Dog Bat Lion Bird
L Bi
In the case of collection we can see that the search traverses across the entire collection to get the required object. But in the case of map it is directly accessed using the key.
74
Map Interface
Map interface is the root interface in the map hierarchy All map implementations should implement this interface directly or indirectly. Important Methods:
Methods Description void clear() Removes all mappings from this map (optional operation). boolean containsKey(Object key) Returns true if this map contains a mapping for the specified key. boolean containsValue(Object value) Returns true if this map maps one or more keys to the specified value. Set entrySet() Returns a set view of the mappings contained in this map. Object get(Objectkey) Returns the value to which this map maps the specified key.
75
Description Returns a set with all the keys contained in this map. Associates the specified value with the specified key in this map.
void putAll(Map t) Copies all of the mappings from the specified map to this map Object remove(Object key) Removes the mapping for this key from this map if it is present int size() Returns the number of key-value mappings in this map. Collection values() Returns a collection with all the values contained in this map.
76
HashMap
Implementation of the Map interface. Permits null values for key(only one key) and value. Not Thread safe. Does not maintain the order of elements in the Map.
77
Syntax: Map<Type1,Type2> mapName=new HashMap<Type1,Type2>(); Creates a map with generics defined key of the type Type1 and value of the type Type2. Example: Creates map object supporting Integer key and String value. Map<Integer,String> myMap=new HashMap<Integer,String>();
Always remember to declare the Map using the appropriate interface. In the example it is Map. 78
Adding Elements to a Map: Elements can be added to a map as key - value pairs using the put() method Syntax : map.put(key,value); Example: map.put(1,India); // This adds an country India with a key value 1. Reading Elements From a Map: Elements can be retrieved from a map by passing the key using the get() method. Syntax : variable =map.get(key); Example: String country=map.get(1); // This retrieves the country specific to key 1 which is India. 79
keySet() method
keySet() returns the set of keys for the map Using the keys obtained one can iterate the map. Set<Integer> keys=map.keySet(); Iterator<Integer> iterator=keys.iterator(); while(iterator.hasNext()) { System.out.println(iterator.next()); }
Get the iterator of the Set. Iterating the set and printing the key values. Get the keys of the Map.
80
81
Create a class named MapEx. It should loads a map with student registration number as key and student name as value and returns the student map.
Always remember to declare the Map using the appropriate interface. In the example it is Map. 82
Let us now iterate through the map and print the name and the registration number.
Prints the map Gets the key Set for the map Gets the iterator for the keyset Iterates over the key set and reads the value for each key.
83
What can be done to automatically sort the map according to the registration number ? The solution is TreeMap, since Tree implements the SortedMap interface, it automatically stores the elements in a sorted order based on the key.
84
Note : See how easily we changed the implementation from HashMap to TreeMap by making just one change. This is the advantage of declaring collections with the interface Map. 85
Notice the output the student records are displayed based on the registration number order.
86
Time To Reflect
Associates to reflect the following before proceeding. What types of map can be used to if want to allow null values? Suppose you are asked to create a telephone directory with person's name in a sorted order which map implementation do you prefer to use ?
87
User defined classes can be stored in any of the collections like list , set map etc.
In the next lend a hand we will see how user defined objects can be added and retrieved from an ArrayList. Same procedure applies for all other collections. NOTE: To add a user defined object to a sorted collection developers should either Make the User Defined object to implement Comparable interface (or) Create a custom comparator class and pass it as constructor parameter when creating the collection object. Refer the following links for more details : http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Comparable.html http://docs.oracle.com/javase/1.3/docs/api/java/util/Comparator.html 88
Consider a scenario in which you want to send the details of students to a method. The student details includes roll number , name , address, phone number and email id. Suppose there are 50 students what can be done to pass the details of all the 50 students together ? Let us see how to solve it? Step 1 : Create a Student class with the roll number, name , address as its fields. Step 2 : Create an object of Student class for each student and load the details. Step 3 : Create an ArrayList and add each of the Student objects to the list. Step 4 : Pass the list as argument to the method.
89
Let us create a StudentManager class with method printStudentDetails() accepts the student details as a list of student objects. Components to be developed: 1. Student Class : For holding the student details. 2. StudentManager class : Contains method for printing the student details. 3. MainClass class : Creates 5 student objects , adds them to a list and pass it to the printStudentDetails() method of the StudentManager class.
90
The Student class should have the following fields to hold the student details 1. roll number 2. name 3. address 4. phone number 5. email id All the fields should be created as private and accessed using public methods.
91
All the methods starting with the word get are used to read the associated field value. Example : getName() returns the name. The values to the member variables can be initialized using the overloaded constructor.
92
Creates ArrayList objects and adds the student objects to the list. Passes the list as input to printStudentDetails method
93
94
Core Java