Collections in java is a framework that provides an architecture to store and manipulate the group of objects. 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).
What is Collection in java : Collection represents a single unit of objects i.e. a group.
What is framework in java :
- provides readymade architecture.
- represents set of classes and interface.
- is optional.
What is Collection framework
Collection framework represents a unified architecture for storing and manipulating
group of objects. It has :
- Interfaces and its implementations i.e. classes
- Algorithm
The collections framework was designed to meet several goals, such as −
1) The framework had to be high-performance. The implementations for the
fundamental collections (dynamic arrays, linked lists, trees, and hash tables)
were to be highly efficient.
2) The framework had to allow different types of collections to work in a similar
manner and with a high degree of interoperability.
3) The framework had to extend and/or adapt a collection easily.
Methods | Description |
---|---|
public boolean add(Object element) | Used to insert an element in this collection |
public boolean addAll(Collection c) | Used to insert the specified collection elements in the invoking collection |
public boolean remove(Object element) | Used to delete an element from this collection |
public boolean removeAll (Collection c) | Used to delete all the elements of specified collection from the invoking collection |
public boolean retainAll(Collection c) | Used to delete all the elements of invoking collection except the specified collection |
public int size() | Return the total number of elements in the collection |
public void clear() | Removes the total no of element from the collection |
public boolean contains(Object element) | Used to search an element |
public boolean containsAll (Collection c) | Used to search the specified collection in this collection |
public Iterator iterator() | Returns an iterator |
public Object[] toArray() | Converts collection into array |
public boolean isEmpty() | Checks if collection is empty |
public boolean equals(Object element) | Matches two collection |
public int hashCode() | Returns the hashcode number for collection |
Iterator interface
Iterator interface provides the facility of iterating the elements in forward direction only.
Methods | Description |
---|---|
public boolean hasNext() | It returns true if iterator has more elements |
public Object next() | It returns the element and moves the cursor pointer to the next element |
public void remove() | It removes the last elements returned by the iterator. It is rarely used |
Java – The List Interface
Overview of List collection
Basically, a list collection stores elements by insertion order (either at the end or at a specific position in the list). A list maintains indices of its elements so it allows adding, retrieving, modifying, removing elements by an integer index (zero based index; the first element is at 0-index, the second at 1-index, the third at 2-index, and so on). The following picture illustrates a list that stores some String elements:
A list can store objects of any types. Primitive types are automatically converted to corresponding wrapper types, e.g. integer numbers are converted to Integer objects. It allows null and duplicate elements, and orders them by their insertion order (index).
The List is the base interface for all list types, and the ArrayList and LinkedList classes are two common List’s implementations.
- ArrayList : An implementation that stores elements in a backing array. The array’s size will be automatically expanded if there isn’t enough room when adding new elements into the list. It’s possible to set the default size by specifying an initial capacity when creating a new ArrayList.
- LinkedList : An implementation that stores elements in a doubly-linked list data structure. It offers constant time for adding and removing elements at the end of the list; and linear time for operations at other positions in the list. Therefore, we can consider using a LinkedList if fast adding and removing elements at the end of the list is required.
The following class diagram depicts the inheritance tree of the List collections:
Java ArrayList class
Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class and implements List interface. The important points about Java ArrayList class are:
- Java ArrayList class can contain duplicate elements.
- Java ArrayList class maintains insertion order.
- Java ArrayList class is non synchronized.
- Java ArrayList allows random access because array works at the index basis.
- 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.
Constructor | Description |
---|---|
ArrayList() | It is used to build an empty array list |
ArrayList(Collection c) | It is used to build an array list that is initialized with the elements of the collection c |
ArrayList(int capacity) | It is used to build an array list that has the specified initial capacity |
Method | Description |
---|---|
void add(int index, Object element) | It is used to insert the specified element at the specified position index in a list |
boolean addAll(Collection c) | It is used to append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s iterator |
void clear() | It is used to remove all of the elements from this list |
int lastIndexOf(Object o) | It is used to return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element |
Object[] toArray() | It is used to return an array containing all of the elements in this list in the correct order |
Object[] toArray(Object[] a) | If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list |
boolean add(Object o) | It is used to append the specified element to the end of a list |
boolean addAll(int index, Collection c) | It is used to insert all of the elements in the specified collection into this list, starting at the specified position |
Object clone() | It is used to return a shallow copy of an ArrayList |
int indexOf(Object o) | It is used to return the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element |
void trimToSize() | It is used to trim the capacity of this ArrayList instance to be the list’s current size |
Java Non-generic Vs Generic Collection
Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic. Java new generic collection allows you to have only one type of object in collection. Now it is type safe so typecasting is not required at run time.
Let’s see the old non-generic example of creating java collection.
ArrayList al=new ArrayList(); //creating old non-generic arraylist
Let’s see the new generic example of creating java collection.
ArrayList<String> al=new ArrayList<String>(); //creating new generic arraylist
In generic collection, we specify the type in angular braces. Now ArrayList is forced to have only specified type of objects in it. If you try to add another type of object, it gives compile time error.
Java ArrayList Example
import java.util.*;
class TestCollection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>(); //Creating arraylist
list.add("Ravi");
//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Java LinkedList class
Java LinkedList class uses doubly linked list to store the elements. It provides a linked-list data structure. It inherits the AbstractList class and implements List and Deque interfaces. The important points about Java LinkedList are:
- Java LinkedList class can contain duplicate elements.
- Java LinkedList class maintains insertion order.
- Java LinkedList class is non synchronized.
- In Java LinkedList class, manipulation is fast because no shifting needs to be occurred.
- Java LinkedList class can be used as list, stack or queue.
Hierarchy of LinkedList class
As shown in above diagram, Java LinkedList class extends AbstractSequentialList class and implements List and Deque interfaces.
Doubly Linked List : In case of doubly linked list, we can add or remove elements from both side.
Constructor | Description |
---|---|
LinkedList() | It is used to construct an empty list |
LinkedList(Collection c) | It is used to construct a list containing the elements of the specified collection, in the order they are returned by the collection’s iterator |
Method | Description |
---|---|
void add(int index, Object element) | It is used to insert the specified element at the specified position index in a list |
void addFirst(Object o) | It is used to insert the given element at the beginning of a list |
void addLast(Object o) | It is used to append the given element to the end of a list |
int size() | It is used to return the number of elements in a list |
boolean add(Object o) | It is used to append the specified element to the end of a list |
boolean contains(Object o) | It is used to return true if the list contains a specified element |
boolean remove(Object o) | It is used to remove the first occurence of the specified element in a list |
Object getFirst() | It is used to return the first element in a list |
Object getLast() | It is used to return the last element in a list |
int indexOf(Object o) | It is used to return the index in a list of the first occurrence of the specified element, or -1 if the list does not contain any element |
int lastIndexOf(Object o) | It is used to return the index in a list of the last occurrence of the specified element, or -1 if the list does not contain any element |
Java LinkedList Example
import java.util.*;
public class TestCollection7{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ravi
Vijay
Ravi
Ajay
Difference between ArrayList and LinkedList
ArrayList and LinkedList both implements List interface and maintains insertion order. Both are non synchronized classes. But there are many differences between ArrayList and LinkedList classes that are given below :
ArrayList | LinkedList |
---|---|
1) ArrayList internally uses dynamic array to store the elements. | LinkedList internally uses doubly linked list to store the elements. |
2) Manipulation with ArrayList is slow because it internally uses array. If any element is removed from the array, all the bits are shifted in memory. | Manipulation with LinkedList is faster than ArrayList because it uses doubly linked list so no bit shifting is required in memory. |
3) ArrayList class can act as a list only because it implements List only. | LinkedList class can act as a list and queue both because it implements List and Deque interfaces. |
4) ArrayList is better for storing and accessing data. | LinkedList is better for manipulating data. |
Java – The Set Interface
A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction. The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited. Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ.
The methods declared by Set are summarized in the following table −
Method | Description |
---|---|
add( ) | Adds an object to the collection |
clear( ) | Removes all objects from the collection |
contains( ) | Returns true if a specified object is an element within the collection |
isEmpty( ) | Returns true if the collection has no elements |
iterator( ) | Returns an Iterator object for the collection, which may be used to retrieve an object |
remove( ) | Removes a specified object from the collection |
size( ) | Returns the number of elements in the collection |
Java HashSet class
Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the AbstractSet class and implements Set interface.
The important points about Java HashSet class are:
1) HashSet stores the elements by using a mechanism called hashing.
2) HashSet contains unique elements only.
Difference between List and Set : List can contain duplicate elements whereas Set contains unique elements only.
Constructor | Description |
---|---|
HashSet() | It is used to construct a default HashSet |
HashSet(Collection c) | It is used to initialize the hash set by using the elements of the collection c |
HashSet(int capacity) | It is used to initialize the capacity of the hash set to the given integer value capacity. The capacity grows automatically as elements are added to the HashSet |
Method | Description |
---|---|
void clear() | It is used to remove all of the elements from this set |
boolean contains(Object o) | It is used to return true if this set contains the specified element |
boolean add(Object o) | It is used to adds the specified element to this set if it is not already present |
boolean isEmpty() | It is used to return true if this set contains no elements |
boolean remove(Object o) | It is used to remove the specified element from this set if it is present |
Object clone() | It is used to return a shallow copy of this HashSet instance: the elements themselves are not cloned |
Iterator iterator() | It is used to return an iterator over the elements in this set |
int size() | It is used to return the number of elements in this set |
Java HashSet Example
import java.util.*;
class TestCollection9{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ajay
Vijay
Ravi
Java LinkedHashSet class
Java LinkedHashSet class is a Hash table and Linked list implementation of the set interface. It inherits HashSet class and implements Set interface.
The important points about Java LinkedHashSet class are:
1) Contains unique elements only like HashSet.
2) Provides all optional set operations, and permits null elements.
3) Maintains insertion order.
Constructor | Description |
---|---|
HashSet() | It is used to construct a default HashSet |
HashSet(Collection c) | It is used to initialize the hash set by using the elements of the collection c |
LinkedHashSet(int capacity) | It is used to initialize the capacity of the linkedhashset to the given integer value capacity |
LinkedHashSet(int capacity,float fillRatio) | It is used to initialize both the capacity and the fill ratio(also called load capacity) of the hash set from its argument |
Example of LinkedHashSet class:
import java.util.*;
class TestCollection10{
public static void main(String args[]){
LinkedHashSet<String> al=new LinkedHashSet<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Java TreeSet class
Java TreeSet class implements the Set interface that uses a tree for storage. It inherits AbstractSet class and implements NavigableSet interface. The objects of TreeSet class are stored in ascending order.
The important points about Java TreeSet class are:
1) Contains unique elements only like HashSet.
2) Access and retrieval times are quiet fast.
3) Maintains ascending order.
Constructor | Description |
---|---|
TreeSet() | It is used to construct an empty tree set that will be sorted in an ascending order according to the natural order of the tree set |
TreeSet(Collection c) | It is used to build a new tree set that contains the elements of the collection c |
TreeSet(Comparator comp) | It is used to construct an empty tree set that will be sorted according to given comparator |
TreeSet(SortedSet ss) | It is used to build a TreeSet that contains the elements of the given SortedSet |
Method | Description |
---|---|
boolean addAll(Collection c) | It is used to add all of the elements in the specified collection to this set |
boolean contains(Object o) | It is used to return true if this set contains the specified element |
boolean isEmpty() | It is used to return true if this set contains no elements |
boolean remove(Object o) | It is used to remove the specified element from this set if it is present |
void add(Object o) | It is used to add the specified element to this set if it is not already present |
void clear() | It is used to remove all of the elements from this set |
Object clone() | It is used to return a shallow copy of this TreeSet instance |
Object first() | It is used to return the first (lowest) element currently in this sorted set |
Object last() | It is used to return the last (highest) element currently in this sorted set |
int size() | It is used to return the number of elements in this set |
Java TreeSet Example
import java.util.*;
class TestCollection11{
public static void main(String args[]){
//Creating and adding elements
TreeSet<String> al=new TreeSet<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
//Traversing elements
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ajay
Ravi
Vijay
Java – The Map Interface
The Map interface maps unique keys to values. A key is an object that you use to retrieve a value at a later date.
- Given a key and a value, you can store the value in a Map object. After the value is stored, you can retrieve it by using its key.
- Several methods throw a NoSuchElementException when no items exist in the invoking map.
- A ClassCastException is thrown when an object is incompatible with the elements in a map.
- A NullPointerException is thrown if an attempt is made to use a null object and null is not allowed in the map.
- An UnsupportedOperationException is thrown when an attempt is made to change an unmodifiable map.
Method | Description |
---|---|
void clear( ) | Removes all key/value pairs from the invoking map |
boolean containsKey(Object k) | Returns true if the invoking map contains k as a key. Otherwise, returns false |
boolean containsValue(Object v) | Returns true if the map contains v as a value. Otherwise, returns false |
Set entrySet( ) | Returns a Set that contains the entries in the map. The set contains objects of type Map.Entry . This method provides a set-view of the invoking map |
boolean equals(Object obj) | Returns true if obj is a Map and contains the same entries. Otherwise, returns false |
Object get(Object k) | Returns the value associated with the key k |
int hashCode( ) | Returns the hash code for the invoking map |
boolean isEmpty( ) | Returns true if the invoking map is empty. Otherwise, returns false |
Set keySet( ) | Returns a Set that contains the keys in the invoking map. This method provides a set-view of the keys in the invoking map |
Object put(Object k, Object v) | Puts an entry in the invoking map, overwriting any previous value associated with the key. The key and value are k and v, respectively. Returns null if the key did not already exist. Otherwise, the previous value linked to the key is returned |
void putAll(Map m) | Puts all the entries from m into this map |
Object remove(Object k) | Removes the entry whose key equals k |
int size( ) | Returns the number of key/value pairs in the map |
Collection values( ) | Returns a collection containing the values in the map. This method provides a collection-view of the values in the map |
Java HashMap class
Java HashMap class implements the map interface by using a hashtable. It inherits AbstractMap class and implements Map interface.
The important points about Java HashMap class are:
1) A HashMap contains values based on the key.
2) It contains only unique elements.
3) It may have one null key and multiple null values.
4) It maintains no order.
Constructor | Description |
---|---|
HashMap() | It is used to construct a default HashMap |
HashMap(Map m) | It is used to initializes the hash map by using the elements of the given Map object m |
HashMap(int capacity) | It is used to initializes the capacity of the hash map to the given integer value, capacity |
HashMap(int capacity, float fillRatio) | It is used to initialize both the capacity and fill ratio of the hash map by using its arguments |
Method | Description |
---|---|
void clear() | It is used to remove all of the mappings from this map |
boolean containsKey(Object key) | It is used to return true if this map contains a mapping for the specified key |
boolean containsValue(Object value) | It is used to return true if this map maps one or more keys to the specified value |
boolean isEmpty() | It is used to return true if this map contains no key-value mappings |
Object clone() | It is used to return a shallow copy of this HashMap instance: the keys and values themselves are not cloned |
Set entrySet() | It is used to return a collection view of the mappings contained in this map |
Set keySet() | It is used to return a set view of the keys contained in this map |
Object put(Object key, Object value) | It is used to associate the specified value with the specified key in this map |
int size() | It is used to return the number of key-value mappings in this map |
Collection values() | It is used to return a collection view of the values contained in this map |
Java HashMap Example
import java.util.*;
class TestCollection13{
public static void main(String args[]){
HashMap<Integer,String> hm=new HashMap<Integer,String>();
hm.put(100,"Amit");
hm.put(101,"Vijay");
hm.put(102,"Rahul");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:
102 Rahul
100 Amit
101 Vijay