Yadab Raj Ojha
Sr. Java Developer / Lecture
Email:
[email protected]Blog: http://yro-tech.blogspot.com/
Java Tutorial: https://github.com/yrojha4ever/JavaStud
LinkedIn: https://www.linkedin.com/in/yrojha
Twitter: https://twitter.com/yrojha4ever
Website: https://www.javaenvagilist.com
Part 4
Collections and Generics
200
@Author: YROJHA
Collections and Generics
Collections
Hierarchy and methods
Iterator interface
List: ArrayList, LinkedList, Vector
Set: HashSet, LinkedHashSet, TreeSet
Map: HashMap, TreeMap, LinkedHashMap
Iterator/ ListIterator
201
@Author: YROJHA
Collections in Java
Collections in java is a framework that provides an architecture to store and manipulate the group of
objects. Collections are like containers that groups multiple items in a single unit. For example; a jar of
chocolates, list of names etc.
All the operations that you perform on a data such as searching, sorting, insertion, manipulation,
deletion etc. can be performed by Java Collections.
Java Collection simply means a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList, PriorityQueue,
HashSet, LinkedHashSet, TreeSet etc).
Hierarchy of Collection Framework
Let us see the hierarchy of collection framework.The java.util package contains all the classes and
interfaces for Collection framework.
Methods of Collection interface
There are many methods declared in the Collection interface. They are as follows:
202
@Author: YROJHA
No. Method Description
1 public boolean add(Object element) is used to insert an element in this collection.
2 public boolean addAll(collection c) is used to insert the specified collection
elements in the invoking collection.
3 public boolean remove(Object element) is used to delete an element from this
collection.
4 public boolean removeAll(Collection c) is used to delete all the elements of specified
collection from the invoking collection.
5 public boolean retainAll(Collection c) is used to delete all the elements of invoking
collection except the specified collection.
6 public int size() return the total number of elements in the
collection.
7 public void clear() removes the total no of element from the
collection.
8 public boolean contains(object element) is used to search an element.
9 public boolean containsAll(Collection c) is used to search the specified collection in this
collection.
10 public Iterator iterator() returns an iterator.
11 public Object[] toArray() converts collection into array.
12 public boolean isEmpty() checks if collection is empty.
13 public boolean equals(Object element) matches two collection.
14 public int hashCode() returns the hashcode number for collection.
203
@Author: YROJHA
Iterator interface
Iterator interface provides the facility of iterating the elements in forward direction only.
There are only three methods in the Iterator interface. They are:
1. public boolean hasNext() it returns true if iterator has more elements.
2. public object next() it returns the element and moves the cursor pointer to the next element.
3. public void remove() it removes the last elements returned by the iterator.
Prior to Java SE 5, if you wanted to insert a primitive value into a data structure, you had to create a new
object of the corresponding type-wrapper class, then insert it in the collection. Similarly, if you wanted to
retrieve an object of a type-wrapper class from a collection and manipulate its primitive value, you had to
invoke a method on the object to obtain its corresponding primitive-type value.
List: (ArrayList, LinkedList, Vector )
Java ArrayList class
o Java ArrayList class uses a dynamic array for storing the elements. It extends AbstractList class
and implements List interface.
o Java ArrayList class can contain duplicate elements.
o Java ArrayList class maintains insertion order.
o Java ArrayList class is non synchronized.
o Java ArrayList allows random access because array works at the index basis.
o In Java ArrayList class, manipulation is slow because a lot of shifting needs to be occurred if any
element is removed from the array list.
204
@Author: YROJHA
205
@Author: YROJHA
User-defined class objects
Java LinkedList class
o Java LinkedList class uses doubly linked list to store the elements. It extends the AbstractList
class and implements List and Deque interfaces.
LinkedList<String> al=new LinkedList<String>();
ArrayList LinkedList
1) ArrayList internally uses dynamic array to LinkedList internally uses doubly linked
store the elements. list to store the elements.
2) Manipulation with ArrayList is slow because Manipulation with LinkedList is faster than
it internally uses array. If any element is ArrayList because it uses doubly linked list so
removed from the array, all the bits are shifted no bit shifting is required in memory.
in memory.
206
@Author: YROJHA
3) ArrayList class can act as a list only LinkedList class can act as a list and
because it implements List only. queue both because it implements List and
Deque interfaces.
4) ArrayList is better for storing and LinkedList is better for manipulating data.
accessing data.
Vector:
Vector is synchronized which means it is suitable for thread-safe operations but it gives poor
performance when used in multi-thread environment. It is recommended to use ArrayList (it is non-
synchronized, gives good performance) in place of Vector when there is no need of thread-safe
operations.
207
@Author: YROJHA
Set (HashSet, LinkedHashSet, TreeSet)(Contain unique and sorted elements)
The Java platform contains three general-purpose Set implementations: HashSet, TreeSet, and
LinkedHashSet. Set interface doesn’t allow random-access to an element in the Collection. You can use
iterator or foreach loop to traverse the elements of a Set.
Java HashSet class
o uses hashtable to store the elements. It extends AbstractSet class and implements Set
interface.
o contains unique elements only.
208
@Author: YROJHA
LinkedHashSet:
LinkedHashSet is also an implementation of Set interface.
1. HashSet doesn’t maintain any kind of order of its elements.
2. TreeSet sorts the elements in ascending order.
3. LinkedHashSet maintains the insertion order. Elements gets sorted in the same sequence in
which they have been added to the Set.
TreeSet
TreeSet is similar to HashSet except that it sorts the elements in the ascending order while HashSet
doesn’t maintain any order. TreeSet allows null element but like HashSet it doesn’t allow. Like most of
the other collection classes this class is also not synchronized, however it can be synchronized explicitly
like this: SortedSet s = Collections.synchronizedSortedSet(new TreeSet(...));
209
@Author: YROJHA
Map
A Map is an object that maps keys to values. A map cannot contain duplicate keys. There
are three main implementations of Map interfaces: HashMap, TreeMap, and
LinkedHashMap.
HashMap: it makes no guarantees concerning the order of iteration
TreeMap: It stores its elements in a red-black tree, orders its elements based on their
values; it is substantially slower than HashMap.
LinkedHashMap: It orders its elements based on the order in which they were inserted
into the set (insertion-order).
HashMap
TreeMap
LinkedHashMap
210
@Author: YROJHA
HashMap
HashMap is a Map based collection class that is used for storing Key & value pairs. This class makes no
guarantees as to the order of the map. It is similar to the Hashtable class except that it is
unsynchronized and permits nulls(null values and null key).
211
@Author: YROJHA
TreeMap
TreeMap is Red-Black tree based NavigableMap implementation. TreeMap is sorted in the
ascending order of its keys. TreeMap is unsynchronized collection class which means it is not
suitable for thread-safe operations until unless synchronized explicitly.
LinkedHashMap
LinkedHashMap is a Hash table and linked list implementation of the Map interface, with
predictable iteration order.
HashMap doesn’t maintain any order.
TreeMap sort the entries in ascending order of keys.
LinkedHashMap maintains the insertion order.
212
@Author: YROJHA
Iterator/ListIterator
Both Iterator and ListIterator are used to iterate through elements of a collection class. Using
Iterator we can traverse in one direction (forward) while using ListIterator we can traverse the
collection class on both the directions(backward and forward).
Methods: hasPrevious, previous, hasNext, next
213
@Author: YROJHA
Collections Methods:
Class Collections provides several high-performance algorithms for manipulating collection
elements. The algorithms are implemented as static methods. The methods sort, binarySearch,
reverse, shuffle, fill and copy operate on Lists. Methods min, max, addAll, frequency and
disjoint operate on Collections.
214
@Author: YROJHA
Sorting in Descending Order
215
@Author: YROJHA