top of page
hand-businesswoman-touching-hand-artificial-intelligence-meaning-technology-connection-go-

Java collections framework


Introduction







Before understanding the different components in the above framework, let’s first understand a class and an interface.

· Class: A class is a user-defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type.

· Interface: Like a class, an interface can have methods and variables, but the methods declared in an interface are by default abstract (only method signature, no body). Interfaces specify what a class must do and not how. It is the blueprint of the class.

Collection Interfaces

The collection interfaces are divided into two groups. The most basic interface, java.util.Collection, has the following descendants:

The other collection interfaces are based on java.util.Map and are not true collections. However, these interfaces contain collection-view operations, which enable them to be manipulated as collections. Map has the following offspring:

Many of the modification methods in the collection interfaces are labeled optional. Implementations are permitted to not perform one or more of these operations, throwing a runtime exception (UnsupportedOperationException) if they are attempted. The documentation for each implementation must specify which optional operations are supported. Several terms are introduced to aid in this specification:

· Collections that do not support modification operations (such as add, remove and clear) are referred to as unmodifiable. Collections that are not unmodifiable are modifiable.

· Collections that additionally guarantee that no change in the Collection object will be visible are referred to as immutable. Collections that are not immutable are mutable.

· Lists that guarantee that their size remains constant even though the elements can change are referred to as fixed-size. Lists that are not fixed-size are referred to as variable-size.

· Lists that support fast (generally constant time) indexed element access are known as random access lists. Lists that do not support fast indexed element access are known as sequential access lists. The RandomAccess marker interface enables lists to advertise the fact that they support random access. This enables generic algorithms to change their behavior to provide good performance when applied to either random or sequential access lists.

Some implementations restrict what elements (or in the case of Maps, keys and values) can be stored. Possible restrictions include requiring elements to:

· Be of a particular type.

· Be not null.

· Obey some arbitrary predicate.

Attempting to add an element that violates an implementation's restrictions results in a runtime exception, typically a ClassCastException, an IllegalArgumentException, or a NullPointerException. Attempting to remove or test for the presence of an element that violates an implementation's restrictions can result in an exception. Some restricted collections permit this usage.

List Interface

List interface is the child interface of Collection interface. It inhibits a list type data structure in which we can store the ordered collection of objects. It can have duplicate values.

List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.

To instantiate the List interface, we must use :


List <data-type> list1= new ArrayList();

List <data-type> list2 = new LinkedList();

List <data-type> list3 = new Vector();

List <data-type> list4 = new Stack();

There are various methods in List interface that can be used to insert, delete, and access the elements from the list.


ArrayList

The ArrayList class implements the List interface. It uses a dynamic array to store the duplicate element of different data types. The ArrayList class maintains the insertion order and is non-synchronized. The elements stored in the ArrayList class can be randomly accessed. Consider the following example.

  1. import java.util.*;

  2. class TestJavaCollection1{

  3. public static void main(String args[]){

  4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist

  5. list.add("SQL");//Adding object in arraylist

  6. list.add("JAVA");

  7. list.add("SELENIUM");

  8. list.add("PYTHON");

  9. //Traversing list through Iterator

  10. Iterator itr=list.iterator();

  11. while(itr.hasNext()){

  12. System.out.println(itr.next());

  13. }

  14. }

  15. }

Vector

Vector uses a dynamic array to store the data elements. It is similar to ArrayList. However, It is synchronized and contains many methods that are not the part of Collection framework.

Consider the following example.

  1. import java.util.*;

  2. public class TestJavaCollection3{

  3. public static void main(String args[]){

  4. Vector<String> v=new Vector<String>();

  5. v.add("AMY");

  6. v.add("ANT");

  7. v.add("SANT");

  8. v.add("GAIN");

  9. Iterator<String> itr=v.iterator();

  10. while(itr.hasNext()){

  11. System.out.println(itr.next());

  12. }

  13. }

  14. }

Stack

The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e., Stack. The stack contains all of the methods of Vector class and also provides its methods like boolean push(), boolean peek(), boolean push(object o), which defines its properties.

Consider the following example.

  1. import java.util.*;

  2. public class TestJavaCollection4{

  3. public static void main(String args[]){

  4. Stack<String> stack = new Stack<String>();

  5. stack.push("AMY");

  6. stack.push("Gait");

  7. stack.push("AmT");

  8. stack.push("AUDIT");

  9. stack.push("GANG");

  10. stack.pop();

  11. Iterator<String> itr=stack.iterator();

  12. while(itr.hasNext()){

  13. System.out.println(itr.next());

  14. }

  15. }

  16. }

Queue Interface

Queue interface maintains the first-in-first-out order. It can be defined as an ordered list that is used to hold the elements which are about to be processed. There are various classes like PriorityQueue, Deque, and ArrayDeque which implements the Queue interface.

Queue interface can be instantiated as:

  1. Queue<String> q1 = new PriorityQueue();

  2. Queue<String> q2 = new ArrayDeque();

There are various classes that implement the Queue interface, some of them are given below.

PriorityQueue

The PriorityQueue class implements the Queue interface. It holds the elements or objects which are to be processed by their priorities. PriorityQueue doesn't allow null values to be stored in the queue.

Consider the following example.

  1. import java.util.*;

  2. public class TestJavaCollection5{

  3. public static void main(String args[]){

  4. PriorityQueue<String> queue=new PriorityQueue<String>();

  5. queue.add("SAP");

  6. queue.add("ABAP");

  7. queue.add("JAVA");

  8. queue.add("C");

  9. System.out.println("C++:"+queue.element());

  10. System.out.println("SQL:"+queue.peek());

  11. System.out.println("iterating the queue elements:");

  12. Iterator itr=queue.iterator();

  13. while(itr.hasNext()){

  14. System.out.println(itr.next());

  15. }

  16. queue.remove();

  17. queue.poll();

  18. System.out.println("after removing two elements:");

  19. Iterator<String> itr2=queue.iterator();

  20. while(itr2.hasNext()){

  21. System.out.println(itr2.next());

  22. }

  23. }

  24. }

Deque Interface

Deque interface extends the Queue interface. In Deque, we can remove and add the elements from both the side. Deque stands for a double-ended queue which enables us to perform the operations at both the ends.

Deque can be instantiated as:

  1. Deque d = new ArrayDeque();

ArrayDeque

ArrayDeque class implements the Deque interface. It facilitates us to use the Deque. Unlike queue, we can add or delete the elements from both the ends.

ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.

Consider the following example.

  1. import java.util.*;

  2. public class TestJavaCollection6{

  3. public static void main(String[] args) {

  4. //Creating Deque and adding elements

  5. Deque<String> deque = new ArrayDeque<String>();

  6. deque.add("DENT");

  7. deque.add("KENT");

  8. deque.add("ANT”);

  9. //Traversing elements

  10. for (String str : deque) {

  11. System.out.println(str);

  12. }

  13. }

Set Interface

Set Interface in Java is present in java.util package. It extends the Collection interface. It represents the unordered set of elements which doesn't allow us to store the duplicate items. We can store at most one null value in Set. Set is implemented by HashSet, LinkedHashSet, and TreeSet.

Set can be instantiated as:

  1. Set<data-type> s1 = new HashSet<data-type>();

  2. Set<data-type> s2 = new LinkedHashSet<data-type>();

  3. Set<data-type> s3 = new TreeSet<data-type>();

HashSet

HashSet class implements Set Interface. It represents the collection that uses a hash table for storage. Hashing is used to store the elements in the HashSet. It contains unique items.

Consider the following example.

  1. import java.util.*;

  2. public class TestJavaCollection7{

  3. public static void main(String args[]){

  4. //Creating HashSet and adding elements

  5. HashSet<String> set=new HashSet<String>();

  6. set.add("SAP");

  7. set.add("SQL");

  8. set.add("JAVA");

  9. set.add("JMETER");

  10. //Traversing elements

  11. Iterator<String> itr=set.iterator();

  12. while(itr.hasNext()){

  13. System.out.println(itr.next());

  14. }

  15. }

  16. }

LinkedHashSet

LinkedHashSet class represents the LinkedList implementation of Set Interface. It extends the HashSet class and implements Set interface. Like HashSet, It also contains unique elements. It maintains the insertion order and permits null elements.

Consider the following example.

  1. import java.util.*;

  2. public class TestJavaCollection8{

  3. public static void main(String args[]){

  4. LinkedHashSet<String> set=new LinkedHashSet<String>();

  5. set.add(“DEV");

  6. set.add("TESTING");

  7. set.add("FUNC");

  8. set.add("DEV");

  9. Iterator<String> itr=set.iterator();

  10. while(itr.hasNext()){

  11. System.out.println(itr.next());

  12. }

  13. }

  14. }

TreeSet

Java TreeSet class implements the Set interface that uses a tree for storage. Like HashSet, TreeSet also contains unique elements. However, the access and retrieval time of TreeSet is quite fast. The elements in TreeSet stored in ascending order.

Consider the following example:

  1. import java.util.*;

  2. public class TestJavaCollection9{

  3. public static void main(String args[]){

  4. //Creating and adding elements

  5. TreeSet<String> set=new TreeSet<String>();

  6. set.add("ORACLE");

  7. set.add("SELENIUM");

  8. set.add("JMETER");

  9. set.add("JAVA");

  10. //traversing elements

  11. Iterator<String> itr=set.iterator();

  12. while(itr.hasNext()){

  13. System.out.println(itr.next());

  14. }

  15. }

  16. }


Collection Implementations

Classes that implement the collection interfaces typically have names in the form of <Implementation-style><Interface>. The general purpose implementations are summarized in the following table:

Interface : Set, List, Dque, Map

Hash table : Hash set, HaseMap

Resizable Array :ArrayList, ArrayDque

Balance tree : TreeSet, TreeMap

Linked List : LinkedList

HashTable/Linked List : LinkHashSet, LinkHashMap


The general-purpose implementations support all of the optional operations in the collection interfaces and have no restrictions on the elements they may contain. They are unsynchronized, but the Collections class contains static factories called synchronization wrappers that can be used to add synchronization to many unsynchronized collections. All of the new implementations have fail-fast iterators, which detect invalid concurrent modification, and fail quickly and cleanly (rather than behaving erratically).

The AbstractCollection, AbstractSet, AbstractList, AbstractSequentialList and AbstractMap classes provide basic implementations of the core collection interfaces, to minimize the effort required to implement them. The API documentation for these classes describes precisely how each method is implemented so the implementer knows which methods must be overridden, given the performance of the basic operations of a specific implementation.

Methods of Collection interface

There are many methods declared in the Collection interface. They are as follows:

1. public boolean removeAll(Collection<?> c): It is used to delete all the elements of the specified collection from the invoking collection.

2. default boolean removeIf(Predicate<? super E> filter): It is used to delete all the elements of the collection that satisfy the specified predicate.

3. public void clear(): It removes the total number of elements from the collection.

4. public boolean contains(Object element): It is used to search an element.

5. public <T> T[] toArray(T[] a): It converts collection into array. Here, the runtime type of the returned array is that of the specified array.

6. default Spliterator<E> spliterator(): It generates a Spliterator over the specified elements in the collection.

7. public int hashCode(): It returns the hash code number of the collection.

8. public boolean equals(Object element): It matches two collections.

9. retainAll(Collection c): This method is used to retain only the elements in this collection that are contained in the specified collection.

10. size():This method is used to return the number of elements in the collection.

11. spliterator():This method is used to create a Spliterator over the elements in this collection.

12. stream(): This method is used to return a sequential Stream with this collection as its source.


Interfaces that extend the Collections Interface


The collection framework contains multiple interfaces where every interface is used to store a specific type of data. The following are the interfaces present in the framework.

1. Iterable Interface: This is the root interface for the entire collection framework. The collection interface extends the iterable interface. Therefore, inherently, all the interfaces and classes implement this interface. The main functionality of this interface is to provide an iterator for the collections. Therefore, this interface contains only one abstract method which is the iterator. It returns the

Iterator iterator();

2. Collection Interface: This interface extends the iterable interface and is implemented by all the classes in the collection framework. This interface contains all the basic methods which every collection has like adding the data into the collection, removing the data, clearing the data, etc. All these methods are implemented in this interface because these methods are implemented by all the classes irrespective of their style of implementation. And also, having these methods in this interface ensures that the names of the methods are universal for all the collections. Therefore, in short, we can say that this interface builds a foundation on which the collection classes are implemented.

3. 3. List Interface: This is a child interface of the collection interface. This interface is dedicated to the data of the list type in which we can store all the ordered collection of the objects. This also allows duplicate data to be present in it. This list interface is implemented by various classes like ArrayList, Vector, Stack, etc. Since all the subclasses implement the list, we can instantiate a list object with any of these classes. For example,

List <T> al = new ArrayList<> (); List <T> ll = new LinkedList<> (); List <T> v = new Vector<> (); Where T is the type of the object

Summary

Java collections framework is extended by the Apache Commons Collections library, which adds collection types such as a bag and bidirectional map, as well as utilities for creating unions and intersections

The Java collections framework gives the programmer access to prepackaged data structures as well as to algorithms for manipulating them.

A collection is an object that can hold references to other objects. The collection interfaces declare the operations that can be performed on each type of collection.

The classes and interfaces of the collections framework are in package java.util.


Happy Reading!!


48 views0 comments

Recent Posts

See All
bottom of page