Java Collection Framework
- What is Collection?
- Hierarchy of collection framework
- Set vs List vs Map in Java
- When to use List, Set and Map in Java?
- Methods of Collection interface
- Iterator interface
- List Iterator interface
- D/B iterator & List Iterator interface
What is Collection?
- What is Collection?
- Hierarchy of collection framework
- Set vs List vs Map in Java
- When to use List, Set and Map in Java?
- Methods of Collection interface
- Iterator interface
- List Iterator interface
- D/B iterator & List Iterator interface
It is an architecture to store and manipulate the group of objects.
All the operations that you perform on a data such as searching, sorting, insertion, deletion etc. can be performed by Java Collection Framework.
Hierarchy of Collection Framework
Collection consists of,
1.Set - The Set interface extends the Collection interface. It will make sure that an instance of Set contains no duplicate elements. The concrete class implements hashcode and equals methods to make sure uniqueness of objects. Three concrete classes of Set are
-->HashSet,
-->LinkedHashSet and
-->TreeSet.
2.List - The List interface extends Collection to define an ordered collection with duplicates allowed. The List interface adds position-oriented operations, as well as a new list iterator that enables the user to traverse the list bi-directionally.
-->ArrayList,
-->LinkedList and
-->vector
are classes implementing List interface.
3.Queue - A queue is a first-in, first-out data structure. Elements are appended to the end of the queue and are removed from the beginning of the queue.
-->PriorityQueue
-->ArrayDeque
are classes implementing Queue interface.
In a priority queue, elements are assigned priorities. When accessing elements, the element with the highest priority is removed first.
4.Map - A map is a container that stores the elements along with the keys. The keys are like indexes. In List, the indexes are integers. In Map, the keys can be any objects. A map cannot contain duplicate keys. Each key maps to one value. A key and its corresponding value from an entry, which is actually stored in a map.
-->HashMap,
-->HashTable,
-->TreeMap and
-->LinkedHashMap
are classes implementing Map interface.
Set vs List vs Map in Java
Duplicate Objects
Main difference between List and Set interface in Java is that List allows duplicates while Set doesn't allow duplicates. All implementation of Set honor this contract. Map holds two object per Entry e.g. key and value and It may contain duplicate values but keys are always unique.
Order
Another key difference between List and Set is that List is an ordered collection, List's contract maintains insertion order or element. Set is an unordered collection, you get no guarantee on which order element will be stored. Though some of the Set implementation e.g. LinkedHashSet maintains order. Also SortedSet and SortedMap e.g. TreeSet and TreeMap maintains a sorting order, imposed by using Comparator or Comparable.
Null elements
List allows null elements and you can have many null objects in a List, because it also allowed duplicates. Set just allow one nullelement as there is no duplicate permitted while in Map you can have null values and at most one null key. worth noting is thatHashtable doesn't allow null key or values but HashMap allows null values and one null keys. This is also the main difference between these two popular implementation of Map interface, aka HashMap vs Hashtable
Popular implementation
List - ArrayList, LinkedList and Vector
Set - HashSet, TreeSet and LinkedHashSet
Map - HashMap, Hashtable and TreeMap
When to use List, Set and Map in Java
Based upon our understanding of difference between Set, List and Map we can now decide when to use List, Set or Map in Java.
1) If you need to access elements frequently by using index, than List is a way to go. Its implementation e.g. ArrayList provides faster access if you know index.
2) If you want to store elements and want them to maintain an order on which they are inserted into collection then go for List again, as List is an ordered collection and maintain insertion order.
3) If you want to create collection of unique elements and don't want any duplicate than choose any Set implementation e.g.HashSet, LinkedHashSet or TreeSet. All Set implementation follow there general contract e.g. uniqueness but also add addition feature e.g. TreeSet is a SortedSet and elements stored on TreeSet can be sorted by using Comparator or Comparable in Java. LinkedHashSet also maintains insertion order.
4) If you store data in form of key and value than Map is the way to go. You can choose from Hashtable, HashMap, TreeMap based upon your subsequent need. In order to choose between first two see difference between HashSet and HashMap in Java.
Methods of Collection interface
There are many methods declared in the Collection interface. They are as follows:
| 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. |
Iterator interface
Iterator in Java is nothing but a traversing object, made specifically for Collection objects like List and Set. we have already aware about different kind of traversing methods like for-loop ,while loop,do-while,for each lop etc,they all are index based traversing but as we know Java is purely object oriented language there is always possible ways of doing things using objects so Iterator is a way to traverse as well as access the data from the collection.
contains three methods:
boolean hasNext(): this method returns true if this Iterator has more element to iterate.
Object next(): return the next element in the collection until the hasNext() method return true. Its always recommended to call hasNext() method before calling next() method to avoid java.util.NoSuchElementException: Hashtable Iterator
remove(): method remove the last element return by the iterator this method only calls once per call to next().
| ||||
|
List Iterator interface
ListIterator Interface is same as iterator except that list iterator can be used to traverse the element in backward and forward direction.
Methods in ListIterator
1. hashNext()
2. next()
3. previous()
4.hashPrevious()
5. remove()
6. nextIndex()
7. previousIndex()
| Code: | ||
|
Example Output
Elements in forward directiton
23
98
29
71
5
Elements in backward directiton
5
71
29
98
23
D/B iterator & List Iterator interface
1. We can use Iterator to traverse Set and List and also Map type of Objects. But List Iterator can be used to traverse for List type Objects, but not for Set type of Objects.
That is, we can get a Iterrator object by using Set and List, see here :
Iterator ite = Set.iterator();
Iterator ite = List.iterator();
But we get List Iterator object only from List interface, see here :
ListIterator listite = List.listIterator();
i.e., we can't get List Iterator object from Set interface.
2. By using Iterator we can retrieve the elements from Collection Object in forward direction only.
- where as List Iterator, which allows you to traverse in either directions. That is List Iterators traverse two directions. So it has another methods hasPrevious() & previous() other than Iterator.
That is, we can get a Iterrator object by using Set and List, see here :
Iterator ite = Set.iterator();
Iterator ite = List.iterator();
But we get List Iterator object only from List interface, see here :
ListIterator listite = List.listIterator();
i.e., we can't get List Iterator object from Set interface.
2. By using Iterator we can retrieve the elements from Collection Object in forward direction only.
- where as List Iterator, which allows you to traverse in either directions. That is List Iterators traverse two directions. So it has another methods hasPrevious() & previous() other than Iterator.