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 −
· The framework had to be high-performance. The implementations for the fundamental collections (dynamic arrays, linked lists, trees, and hashtables) were to be highly efficient.
· The framework had to allow different types of collections to work in a similar manner and with a high degree of interoperability.
· The framework had to extend and/or adapt a collection easily.
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 interface provides the facility of iterating the elements in forward direction only. |
Methods of Iterator interface
There are only three methods in the Iterator interface. They are:
No. | Method | Description |
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. 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.
o 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.
o 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.
Constructors of Java ArrayList
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. |
Methods of Java ArrayList
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) | It is used to return an array containing all of the elements in this list in the correct order. |
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());
- }
- }
- }
Two ways to iterate the elements of collection in java
There are two ways to traverse collection elements:
- By Iterator interface.
- By for-each loop.
In the above example, we have seen traversing ArrayList by Iterator. Let's see the example to traverse ArrayList elements using for-each loop.
Iterating Collection through for-each loop
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.
Constructors of Java LinkedList
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. |
Methods of Java LinkedList
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
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. |
Example
The above interface has been implemented in various classes like ArrayList or LinkedList, etc. Following is the example to explain few methods from various class implementation of the above collection methods −
import java.util.*; public class CollectionsDemo { public static void main(String[] args) { List a1 = new ArrayList(); a1.add("Zara"); a1.add("Mahnaz"); a1.add("Ayan"); System.out.println(" ArrayList Elements"); System.out.print("\t" + a1); List l1 = new LinkedList(); l1.add("Zara"); l1.add("Mahnaz"); l1.add("Ayan"); System.out.println(); System.out.println(" LinkedList Elements"); System.out.print("\t" + l1); } } This will produce the following result − ArrayList Elements [Zara, Mahnaz, Ayan] LinkedList Elements [Zara, Mahnaz, Ayan]
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 −
Sr.No. | Method & Description |
1 | add( ) Adds an object to the collection. |
2 | clear( ) Removes all objects from the collection. |
3 | contains( ) Returns true if a specified object is an element within the collection. |
4 | isEmpty( ) Returns true if the collection has no elements. |
5 | iterator( ) Returns an Iterator object for the collection, which may be used to retrieve an object. |
6 | remove( ) Removes a specified object from the collection. |
7 | 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:
- HashSet stores the elements by using a mechanism called hashing.
- HashSet contains unique elements only.
Difference between List and Set
List can contain duplicate elements whereas Set contains unique elements only.
Constructors of Java HashSet class:
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. |
Methods of Java HashSet class:
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
1. import java.util.*;
2. class TestCollection9{
3. public static void main(String args[]){
4. //Creating HashSet and adding elements
5. HashSet<String> set=new HashSet<String>();
6. set.add("Ravi");
7. set.add("Vijay");
8. set.add("Ravi");
9. set.add("Ajay");
10. //Traversing elements
11. Iterator<String> itr=set.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
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:
- Contains unique elements only like HashSet.
- Provides all optional set operations, and permits null elements.
- Maintains insertion order.
Constructors of Java LinkedHashSet class
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 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:
1. import java.util.*;
2. class TestCollection10{
3. public static void main(String args[]){
4. LinkedHashSet<String> al=new LinkedHashSet<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ravi");
8. al.add("Ajay");
9. Iterator<String> itr=al.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }
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:
- Contains unique elements only like HashSet.
- Access and retrieval times are quiet fast.
- Maintains ascending order.
Constructors of Java TreeSet class
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. |
Methods of Java TreeSet class
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
1. import java.util.*;
2. class TestCollection11{
3. public static void main(String args[]){
4. //Creating and adding elements
5. TreeSet<String> al=new TreeSet<String>();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10. //Traversing elements
11. Iterator<String> itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. } }
Output:
Ajay
Ravi
Vijay
Example
Set has its implementation in various classes like HashSet, TreeSet, LinkedHashSet. Following is an example to explain Set functionality −
import java.util.*; public class SetDemo { publxic static void main(String args[]) { int count[] = {34, 22,10,60,30,22}; Set<Integer> set = new HashSet<Integer>(); try { for(int i = 0; i < 5; i++) { set.add(count[i]); } System.out.println(set); TreeSet sortedSet = new TreeSet<Integer>(set); System.out.println("The sorted list is:"); System.out.println(sortedSet); System.out.println("The First element of the set is: "+ (Integer)sortedSet.first()); System.out.println("The last element of the set is: "+ (Integer)sortedSet.last()); } catch(Exception e) {} } }
This will produce the following result −
Output
[34, 22, 10, 60, 30]
The sorted list is:
[10, 22, 30, 34, 60]
The First element of the set is: 10
The last element of the set is: 60
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.
Sr.No. | Method & Description |
1 | void clear( ) Removes all key/value pairs from the invoking map. |
2 | boolean containsKey(Object k) Returns true if the invoking map contains k as a key. Otherwise, returns false. |
3 | boolean containsValue(Object v) Returns true if the map contains v as a value. Otherwise, returns false. |
4 | 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. |
5 | boolean equals(Object obj) Returns true if obj is a Map and contains the same entries. Otherwise, returns false. |
6 | Object get(Object k) Returns the value associated with the key k. |
7 | int hashCode( ) Returns the hash code for the invoking map. |
8 | boolean isEmpty( ) Returns true if the invoking map is empty. Otherwise, returns false. |
9 | 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. |
10 | 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. |
11 | void putAll(Map m) Puts all the entries from m into this map. |
12 | Object remove(Object k) Removes the entry whose key equals k. |
13 | int size( ) Returns the number of key/value pairs in the map. |
14 | 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:
- A HashMap contains values based on the key.
- It contains only unique elements.
- It may have one null key and multiple null values.
- It maintains no order.
Constructors of Java HashMap class
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. |
Methods of Java HashMap class
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
1. import java.util.*;
2. class TestCollection13{
3. public static void main(String args[]){
4. HashMap<Integer,String> hm=new HashMap<Integer,String>();
5. hm.put(100,"Amit");
6. hm.put(101,"Vijay");
7. hm.put(102,"Rahul");
8. for(Map.Entry m:hm.entrySet()){
9. System.out.println(m.getKey()+" "+m.getValue());
10. }
11. }
12. }
Output:102 Rahul
100 Amit
101 Vijay
Example
Map has its implementation in various classes like HashMap. Following is an example to explain map functionality −
import java.util.*; public class CollectionsDemo { public static void main(String[] args) { Map m1 = new HashMap(); m1.put("Zara", "8"); m1.put("Mahnaz", "31"); m1.put("Ayan", "12"); m1.put("Daisy", "14"); System.out.println(); System.out.println(" Map Elements"); System.out.print("\t" + m1); } }
This will produce the following result −
Output
Map Elements {Daisy = 14, Ayan = 12, Zara = 8, Mahnaz = 31}
No comments: