MainMenu

Home Java Overview Maven Tutorials

Friday 11 January 2019

Collection in Java

A brief intro of Java Collections



Hello Friends,
In this article , i will describe about collection in Java Language :-

COLLETION IN JAVA
Java collections refer to a single unit of objects.
You can perform all operations on data such as searching, sorting, insertion, manipulation, deletion, etc. by Java collections.
The Collection in Java is a framework that provides an architecture to store and manipulate the group of objects.
Java Collection framework provides many interfaces (Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
What is a Java Collection Framework?
A Java collection framework provides an architecture to store and manipulate a group of objects. A Java collection framework includes the following:
Interfaces
Classes
Algorithm
Let’s learn about them in detail:
Interfaces: Interface in Java refers to the abstract data types. They allow Java collections to be manipulated independently from the details of their representation. Also, they form a hierarchy in object-oriented programming languages.
Classes: Classes in Java are the implementation of the collection interface. It basically refers to the data structures that are used again and again.
Algorithm: Algorithm refers to the methods which are used to perform operations such as searching and sorting, on objects that implement collection interfaces. Algorithms are polymorphic in nature as the same method can be used to take many forms or you can say perform different implementations of the Java collection interface.
The Java collection framework provides the developers to access prepackaged data structures as well as algorithms to manipulate data. Next, let us move to the Java collections framework hierarchy and see where these interfaces and classes resides.

Java Collections : Interface
Iterator interface : Iterator is an interface that iterates the elements. It is used to traverse the list and modify the elements. Iterator interface has three methods which are mentioned below:
public boolean hasNext() – This method returns true if the iterator has more elements.
public object next() – It returns the element and moves the cursor pointer to the next element.
public void remove() – This method removes the last elements returned by the iterator.

There are three components that extend the collection interface i.e List, Queue and Sets. Let’s learn about them in detail:
Java collections: List A List is an ordered Collection of elements which may contain duplicates. It is an interface that extends the Collection interface. Lists are further classified into the following:
ArrayList
LinkedList
Vectors
Let’s go into detail on each one of them:
Array list: ArrayList is the implementation of List Interface where the elements can be dynamically added or removed from the list. Also, the size of the list is increased dynamically if the elements are added more than the initial size.
ArrayList object = new ArrayList ();

Linked List: Linked List is a sequence of links which contains items. Each link contains a connection to another link.
Syntax: Linkedlist object = new Linkedlist();

Java Linked List class uses two types of Linked list to store the elements:
Singly Linked List
Doubly Linked List
Singly Linked List: In a singly Linked list each node in this list stores the data of the node and a pointer or reference to the next node in the list. Refer to the below image to get a better understanding of single Linked list.

Doubly Linked List: In a doubly Linked list, it has two references, one to the next node and another to previous node. You can refer to the below image to get a better understanding of doubly linked list.

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.

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.



A Collection is a group of individual objects represented as a single unit.
Java provides Collection Framework which defines several classes and interfaces to represent a group of objects as a single unit.

The Collection interface (java.util.Collection) and Map interface (java.util.Map)

are the two main “root” interfaces of Java collection classes.

1). List Interface

List alist= new ArrayList();
List llist = new LinkedList();
List vlist = new Vector();
List slist = new Stack();


2).Java Collections – Set
A Set is a Collection that cannot contain duplicate elements. There are three main implementations of Set interface:
HashSet, TreeSet, and LinkedHashSet. HashSet, which stores its elements in a hash table, is the best-performing
implementation; however it makes no guarantees concerning the order of iteration. TreeSet, which stores its elements
in a red-black tree, orders its elements based on their values; it is substantially slower than HashSet. LinkedHashSet,
which is implemented as a hash table with a linked list running through it, orders its elements based on the order in which they
were inserted into the set (insertion-order).

Set hs = new HashSet();
Set ls = new LinkedHashSet();
Set ts = new TreeSet();


3).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 pq = new PriorityQueue();
Queue aq = new ArrayDeque();


ArrayList Example
public class ConsTest
{
public static void main(String args[]) throws IOException
{
ArrayList alist = new ArrayList();
alist.add("chandan");
alist.add("Singh");
alist.add("chauhan");
alist.add("chandan");
Iterator itr = alist.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}

Output :-
chandan
Singh
chauhan
chandan

LinkedList example
public class ConsTest
{
public static void main(String args[]) throws IOException
{
LinkedList alist = new LinkedList();
alist.add("chandan");
alist.add("Singh");
alist.add("chauhan");
alist.add("chandan");
Iterator itr = alist.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}

Output :-
chandan
Singh
chauhan
chandan

Example of Vector :-
public class ConsTest
{
public static void main(String args[]) throws IOException
{
Vector alist = new Vector();
alist.add("chandan");
alist.add("Singh");
alist.add("chauhan");
alist.add("chandan");
Iterator itr = alist.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}

Output :-
chandan
Singh
chauhan
chandan

Example of Stack :-
public class ConsTest
{
public static void main(String args[]) throws IOException
{
Stack stk = new Stack();
stk.push("chandan");
stk.push("Singh");
stk.push("chauhan");
stk.push("chandan");
stk.push("Singh");
stk.pop();
Iterator itr = stk.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}

Output :-
chandan
Singh
chauhan
chandan



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.

package com.lang.beginner;
import java.io.*;
import java.util.ArrayList;
import java.util.*;

public class ConsTest
{
public static void main(String args[])
{
PriorityQueue queue = new PriorityQueue();
queue.add("ChandanSingh");
queue.add("Adhiraaj");
queue.add("Amit");
queue.add("Anngraaj");
System.out.println(queue.element());
System.out.println(queue.peek());
Iterator itr = queue.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
queue.remove();
queue.poll();
System.out.println("After removing elements");
Iterator itr2 = queue.iterator();
while(itr2.hasNext())
{
System.out.println(itr2.next());
}
}
}

Output :-
Adhiraaj
Adhiraaj
Adhiraaj
Anngraaj
Amit
ChandanSingh After removing elements
Anngraaj
ChandanSingh

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

public class ConsTest
{
public static void main(String args[])
{
HashSet hset = new HashSet();
hset.add("chandan");
hset.add("chandan");
hset.add(null);
hset.add("Singh");
Iterator itr = hset.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
Output :-
null
chandan
Singh

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.

public class ConsTest
{
public static void main(String args[])
{
LinkedHashSet hset = new LinkedHashSet();
hset.add("chandan");
hset.add("chandan");
hset.add(null);
hset.add("Singh");
Iterator itr = hset.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
Output :-
chandan
null
Singh



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.

public class ConsTest
{
public static void main(String args[])
{
TreeSet hset = new TreeSet();
hset.add("chandan");
hset.add("chandan");
//hset.add(null);
hset.add("Singh");
Iterator itr = hset.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
Output:-
Singh
chandan









Array ListLinked List
Array List is not SynchronizedLinked List is also not synchronized
Array List maintain insertion orderLinked List Also Maintain insertion order
Array List can have multiple null values and multiple duplicate valuesLinked List can also have multiple null values and multiple duplicate values
ArrayList internally uses a dynamic array to store the elementsLinkedList internally uses a doubly linked list to store the elements.
Manipulation with ArrayList is slow because it internally uses an array. If any element is removed from the array, all the other elements are shifted in memoryManipulation with LinkedList is faster than ArrayList because it uses a doubly linked list, so no bit shifting is required in memory.
When read scenarios are more as complare to add and remove scenario, then linked list preferred When Add remove scenarios are more than read scenarios then linked list preferred






HashSetLinkedHashsetTreeset
HashSet uses hashmap for it’s internal storageLinkedHashSet extends HashSet class and implements Set interface and use HashMap internally to store it's elementTreeSet extends AbstractSet and implements NavigableSet interface use TreeMap internally to store it's element
Hashset does not maintains any orderLinked HashSet maintains insertion ordermaintains ascending order of inserted items
HashSet represents a group of unique elementsLinkedHashSet represents a group of unique elementsit also represents a group of unique elements
HashSet can have one null valueLinkedHashSet can also have one null valueNo null values allows in TreeSet
not synchronized and hence not Thread safenot synchronized and hence not Thread safenot synchronized and hence not Thread safe


When To Use?
1). Use HashSet if you don’t want to maintain any order of elements.
2). Use LinkedHashSet if you want to maintain insertion order of elements.
3). Use TreeSet if you want to sort the elements according to some Comparator.

No comments:

Post a Comment