Category Archives: Core Java

Learn ArrayDeque in Java with Programming Example

ArrayDequeIn this chapter you will learn:

  1. What is ArrayDeque?
  2. Declaration of ArrayDeque
  3. Programming Example
What is ArrayDeque in Java?

ArrayDeque is a resizable array implementation in Deque. Some fact about ArrayDeque are as follow:

  • It is a resizable array implementation in Deque.
  • It has no capacity restriction so it grows as necessary.
  • It is not thread safe
  • It doesn’t allow null element
  • It is faster than stack when used as stack and faster than linked list when used as linked list.

Constructors

Constructors Descriptions
ArrayDeque() Constructs an empty array deque with an initial capacity sufficient to hold 16 elements.
ArrayDeque(Collection<? extends E> c) Constructs a deque containing the elements of the specified collection, in the order they are returned by the collection’s iterator.
ArrayDeque(int numElements) Constructs an empty array deque with an initial capacity sufficient to hold the specified number of elements.

Methods

Methods Descriptions
boolean add(E e) Inserts the specified element at the end of this deque.
void addFirst(E e) Inserts the specified element at the front of this deque.
void addLast(E e) Inserts the specified element at the end of this deque.
void clear() Removes all of the elements from this deque.
ArrayDeque<E> clone() Returns a copy of this deque.
boolean contains(Object o) Returns true if this deque contains the specified element.
Iterator<E> descendingIterator() Returns an iterator over the elements in this deque in reverse sequential order.
E element() Retrieves, but does not remove, the head of the queue represented by this deque.
E getFirst() Retrieves, but does not remove, the first element of this deque.
E getLast() Retrieves, but does not remove, the last element of this deque.
boolean isEmpty() Returns true if this deque contains no elements.
Iterator<E> iterator() Returns an iterator over the elements in this deque.
boolean offer(E e) Inserts the specified element at the end of this deque.
boolean offerFirst(E e) Inserts the specified element at the front of this deque.
boolean offerLast(E e) Inserts the specified element at the end of this deque.
E peek() Retrieves, but does not remove, the head of the queue represented by this deque, or returns null if this deque is empty.
E peekFirst() Retrieves, but does not remove, the first element of this deque, or returns null if this deque is empty.
E peekLast() Retrieves, but does not remove, the last element of this deque, or returns null if this deque is empty.
E poll() Retrieves and removes the head of the queue represented by this deque (in other words, the first element of this deque), or returns null if this deque is empty.
E pollFirst() Retrieves and removes the first element of this deque, or returns null if this deque is empty.
E pollLast() Retrieves and removes the last element of this deque, or returns null if this deque is empty.
E pop() Pops an element from the stack represented by this deque.
void push(E e) Pushes an element onto the stack represented by this deque.
E remove() Retrieves and removes the head of the queue represented by this deque.
boolean remove(Object o) Removes a single instance of the specified element from this deque.
E removeFirst() Retrieves and removes the first element of this deque.
boolean removeFirstOccurrence(Object o) Removes the first occurrence of the specified element in this deque (when traversing the deque from head to tail).
E removeLast() Retrieves and removes the last element of this deque.
boolean removeLastOccurrence(Object o) Removes the last occurrence of the specified element in this deque (when traversing the deque from head to tail).
int size() Returns the number of elements in this deque.
Object[] toArray() Returns an array containing all of the elements in this deque in proper sequence (from first to last element).
<T> T[] toArray(T[] a) Returns an array containing all of the elements in this deque in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.

Methods Inherited From Class

Class Methods
java.util.AbstractCollection addAll(), containsAll(), removeAll(), retainAll(), toString()
java.lang.Object equals(), finalize(), getClass(), hashCode(), notify(), notifyAll(), wait(), wait(), wait()
java.util.Collection addAll(), containsAll(), equals(), hashCode(), removeAll(), retainAll()

Declaration:

ArrayDeque aq=new ArrayDeque();

Programming Example

import java.util.*;
class ArrayDeque_Example
{
  public static void main(String[] args)
  {
    ArrayDeque aq=new ArrayDeque();
    aq.push("C#");
    aq.push("Java");
    aq.push("HTML");
    aq.push("ASP.Net");
    
    //Printing ArrayDeque
    Iterator itr=aq.iterator();
    while(itr.hasNext())
    {
      System.out.print(itr.next()+ " ");
    }
    
    //Removing one Item
    System.out.println("\nItem Removed : " + aq.pop());
    
    //Printing ArrayDeque Again
    System.out.println(aq);
    
    //Adding Element at First Position
    aq.addFirst("PHP");
    //Adding Element at Last Position
    aq.addLast("JavaScript");
    
    //Printing ArrayDeque
    System.out.println(aq);
    
    //Finding Element
    if(aq.contains("Java"))
    {
      System.out.println("Java is found in this list");
    }
  }
}

Output

D:\JavaProgram>javac ArrayDeque_Example.java
D:\JavaProgram>java ArrayDeque_ExampleASP.Net HTML Java C#
Item Removed : ASP.Net
[HTML, Java, C#]
[PHP, HTML, Java, C#, JavaScript]
Java is found in this list
_

Summary

In this chapter you have learned ArrayDeque in Java. It is very easy to learn collection using complete programming example. In the next chapter you will learn Set Interface in Java.


Deque in Java with Programming Example

DequeIn this chapter you will learn:

  1. What is Deque in Java?
  2. Declaration of Deque
  3. Programming Example
What is Deque in Java?

Keyword Deque stands for “Double Ended Queue” which allows insertion and removal of both sides. You can add and remove element both sides as head and tail. However Deque has not size limit but using interface you can restrict its size limit. There are some special methods which allow element’s insertion and removal in both sides. Deque can also be used as Stack. It can behave like LIFO and FIFO both.

Methods

First Element (Head) Last Element (Tail)
Throws Exception Special Value Throws Exception Special Value
Insert addFirst(e) offerFirst(e) addLast(e) offerLast(e)
Insert removeFirst() pollFirst() removeLast() pollLast()
Insert getFirst() peekFirst() getLast() peekLast()

 

Compare Methods (Queue Vs. Deque)

Queue Method Equivalent Deque Method
add(e) addLast(e)
offer(e) offerLast(e)
remove() removeFirst()
poll() pollFirst()
element() getFirst()
peek() peekFirst()
Stack Method Equivalent Deque Method
push(e) addFirst(e)
pop() removeFirst()
peek() peekFirst()
Declaration:
Deque d=new LinkedList();

Programming Example

import java.util.*;
class DeQue_Example
{
  public static void main(String[] args)
  {
    Deque d=new LinkedList();
    
    d.addLast("Tail1");
    d.addLast("Tail2");
    d.addFirst("Head1");
    d.addFirst("Head2");
    
    //Print Deque using Iterator
    Iterator itr=d.iterator();
    while(itr.hasNext())
    {
      System.out.print(itr.next() + " ");
    }
    System.out.println("\nPeek Last Value : "+d.peekLast());
    System.out.println("Remove Last Value : "+d.pollLast());
    //Adding new value to last
    d.addLast("Hello");
    System.out.println("printing : "+d);
  }
}

Output

D:\JavaProgram>javac DeQue_Example.java
D:\JavaProgram>java DeQue_ExampleHead2 Head1 Tail1 Tail2
Peek Last Value : Tail2
Remove Last Value : Tail2
printing : [Head2, Head1, Tail1, Hello]
_

Summary

In this program you can clearly see that Deque allows insertion and removal of elements both sides. It has some special methods that allows programmer to use deque as stack. In the next chapter you will learn about ArrayDeque Class.


PriorityQueue Class in Java with Programming Example

Priority QueueIn this chapter you will learn:

  1. What is PriorityQueue?
  2. Programming Example
 What is PriorityQueue?

Java PriorityQueue are unbounded queue based on priority heap. It store element according to their natural ordering and doesn’t allow null insertion. It is likely as random listing of element in a queue. Important points of PriorityQueue are as follow:

  • It is unbounded and based on Priority heap.
  • However it is unbounded still it has internal capacity to manage size of queue. Size of queue grows automatically if it reaches as maximum elements.
  • Order of elements gets defined based on constructors.
  • Methods, property and iterator are same as queue interface.

 

Constructors and Methods

Constructors Descriptions
PriorityQueue() Creates a PriorityQueue with the default initial capacity (11) that orders its elements according to their natural ordering.
PriorityQueue(Collection<? extends E> c) Creates a PriorityQueue containing the elements in the specified collection.
PriorityQueue(int initialCapacity) Creates a PriorityQueue with the specified initial capacity that orders its elements according to their natural ordering.
PriorityQueue(int initialCapacity,
Comparator<? super E> comparator)
Creates a PriorityQueue with the specified initial capacity that orders its elements according to the specified comparator.
PriorityQueue(PriorityQueue<? extends E> c) Creates a PriorityQueue containing the elements in the specified priority queue.
PriorityQueue(SortedSet<? extends E> c) Creates a PriorityQueue containing the elements in the specified sorted set.

Methods and Descriptions

Methods Descriptions
boolean add(E e) Inserts the specified element into this priority queue.
void clear() Removes all of the elements from this priority queue.
Comparator<? super E> comparator() Returns the comparator used to order the elements in this queue, or null if this queue is sorted according to the natural ordering of its elements.
boolean contains(Object o) Returns true if this queue contains the specified element.
Iterator<E> iterator() Returns an iterator over the elements in this queue.
boolean offer(E e) Inserts the specified element into this priority queue.
E peek() Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
E poll() Retrieves and removes the head of this queue, or returns null if this queue is empty.
boolean remove(Object o) Removes a single instance of the specified element from this queue, if it is present.
int size() Returns the number of elements in this collection.
Object[] toArray() Returns an array containing all of the elements in this queue.
<T> T[] toArray(T[] a) Returns an array containing all of the elements in this queue; the runtime type of the returned array is that of the specified array.

Methods Inherited From Class

Class Methods
java.util.AbstractQueue addAll(), element(), remove()
java.util.AbstractCollection containsAll(), isEmpty(), removeAll(), retainAll(), toString()
java.lang.Object clone(), equals(), finalize(), getClass(), hashCode(), notify(), notifyAll(), wait(), wait(), wait()
java.util.Collection containsAll(), equals(), hashCode(), isEmpty(), removeAll(), retainAll()

Declaration:

PriorityQueue p=new PriorityQueue();

Programming Example

import java.util.*;
class PriorityQueue_Example
{
  public static void main(String[] args)
  {
    PriorityQueue p=new PriorityQueue();
    //Adding Element in PriorityQueue
    p.add("C#");
    p.add("Java");
    p.add("C++");    
    p.add("HTML");
    p.add("VB.Net");
    
    //Printing PriorityQueue
    Iterator itr=p.iterator();
    while(itr.hasNext())
    {
     System.out.print(itr.next()+" "); 
    }
    
    //Adding Elements
    p.add("PHP");
    System.out.println("\n" + p);
    
    //Accessing Top Element
    System.out.println("Top Element is "+ p.element());
    
    //Removing Top Element
    System.out.println("Item Removed : " + p.remove());
    
    //Prining PriorityQueue
    System.out.println(p);
    
  }
}

Output

D:\JavaProgram>javac PriorityQueue_Example.java
D:\JavaProgram>java PriorityQueue_Example

C# HTML C++ Java VB.Net
[C#, HTML, C++, Java, VB.Net, PHP]
Top Element is C#
Item Removed : C#
[C++, HTML, PHP, Java, VB.Net]
_

Summary

In this chapter you have learned about PriorityQueue in Java. It organizes their element order after removing each item. It is mostly used for random listing of elements in a queue. In the next chapter you will learn about Deque Class in Java.


Queue Interface in Java with Programming Example

queueIn this chapter you will learn:

  1. What is queue interface?
  2. Queue Structure
  3. Programming Example
 What is Queue Interface?

Queue is a part of java collection that follows FIFO structure for holding elements. FIFO is based on First In First Out that means the first inserted element will be processed first. There are various real life examples of Queues are:

  • Ticket Counter Queue – The First person in the line gets chance to buy ticket first.
  • Bus Queue – First position bus will start first.
  • Billing Counter – First customer in the line will pay the bill first.

More about Queue

  1. Queue has additional insertion, removal and inspection operations besides on basic collection operations.
  2. Each Queue operation gets terminated by two methods either by throwing exception or by returning special value as null or false.
  3. Each queue has two parts head and tail. Items inserted in queue through tail side and remove item through head side.
  4. Bounded queue holds only specified number of elements.
  5. Add() method is used for inserting element in a queue and remove() or poll() method is used for removing items from queue.
  6. Queue doesn’t allow the insertion of null.
 Methods of Queue Interface
Methods Descriptions
boolean add (E e) This method inserts an element in a queue and returns true if operation successful or return IllegalStateException exception.
E element( ) This method returns element from the top of the queue. It only retrieves element and returns to you. It doesn’t remove element.
boolean offer(E e) This method is also used for adding element in a queue. It is useful when queue is bounded and accept only limit number of element. It returns true if element is added successfully and return false if operation fails. The add(E e)method throws exception when operation gets unsuccessful.
E peek( ) This methods returns element from the top of the queue. The difference between E element() and E peek() method is E peek() returns null if element not found whereas E element throws NoSuchElementExceptionexception.
E poll() This methods removes item from the top of the queue. It returns null if operation gets failed.
E remove() It also removes item from the top of the queue but returnsNoSuchElementException if queue is empty.

Declaration

Queue queue = new LinkedList();

Programming Example

import java.util.*;
class Queue_Example
{
  public static void main(String[] args)
  {
    Queue q=new LinkedList();
    //Adding Item in a queue
    q.add("Java");
    q.add("C#");
    q.add("VB.Net");
    q.add("C++");
    q.add("PHP");
    //Size of Queue
    System.out.println("Size of queue : "+q.size());
    //Displaying Queue
    Iterator itr=q.iterator();
    while(itr.hasNext())
    {
      System.out.print((String)itr.next()+ " ");
    }
   //Retrieving Queue Element
    System.out.println("\nTop Item is "+q.peek());
    //Remove Top Element
    System.out.println("Items Removed "+q.remove());
    //Again printing queue
    System.out.println(q);
    //Size of Queue
    System.out.println("Size of queue : "+q.size());
    //Adding an Item
    q.add("HTML");
    //Printing Queue
    System.out.println(q);
  }
}

Output

Size of queue : 5
Java C# VB.Net C++ PHP
Top Item is Java
Items Removed Java
[C#, VB.Net, C++, PHP]
Size of queue : 4
[C#, VB.Net, C++, PHP, HTML]
_

Summary

In this chapter you learned what the queue interface is in java and their methods and implementation with programming example. In the next chapter you will learn PriorityQueue class.


Stack Class Java with Programming Example

Stack Class JavaIn this chapter you will learn:

  1. What is stack class in java?
  2. How to initialize stack?
  3. Methods of stack class
  4. Programming Example
 What is stack class in Java?

Stack is based on Last-in-First-Out (LIFO) module. It is a subclass of vector class. In the stack the item which is added first in the list can be accessed last and the item which is added last can be accessed first.
For example:

  • Wearing bangles.
  • Stack of CD.
  • Stack of Book etc

How to declare stack?

 public class Stack
   extends Vector

Constructors and methods

It includes all the methods of vector class and it also defines several other methods.

 

Programming Example

import java.util.*;
public class Stack_Example
{
  public static void main(String[] args)
  {
    //Create Empty Stack
    Stack stk=new Stack();
    System.out.println("Items on Stack : " + stk);
    
    //Adding items to Stack
    stk.push("A");
    stk.push("B");
    stk.push("C");
    try
    {
    //Retrieving Stack
    System.out.println("Removing Top Items : " + stk.pop());
    System.out.println("Now items are : " + stk);
    
    System.out.println("Removing Top Items : " + stk.pop());
    System.out.println("Now items are : " + stk);
    
    System.out.println("Removing Top Items : " + stk.pop());
    System.out.println("Now items are : " + stk);
    
    System.out.println("Removing Top Items : " + stk.pop());
    System.out.println("Now items are : " + stk);
    }
    catch(EmptyStackException e)
    {
      System.out.println("Stack Empty");
    }
    
  }
}



Output

D:\JavaProgram>javac Stack_Example.java

D:\JavaProgram>java Stack_Example
Items on Stack : []
Removing Top Items : C
Now items are : [A, B]
Removing Top Items : B
Now items are : [A]
Removing Top Items : A
Now items are : []
Stack Empty
_

Explanation

In the above example we push() method is used for adding items on the stack and pop()method is used for removing items from the top.

Summary

In this chapter you have learned stack class in java collection and their methods with complete programming example. In the next chapter you will learn Queue Interface in Java.


Vector Class Java with Programming Example

Vector ClassIn this chapter you will learn:

  1. What is Vector Class in Java?
  2. Difference between ArrayList and Vector
  3. Initialization of Vector Cass
  4. Methods of Vector Class in Java
  5. Programming Example
 What is Vector Class in Java?

Vector is like an array but the difference is that it can grow and shrink dynamically and doubly. Like an array the element of vector can also be accessed through its index position. It optimizes storage management by maintaining capacity and capacityIncrement. It means if you remove an element the size of vector automatically decreases. Vector Class has synchronized behavior so it gives weak performance in searching, adding, delete and update of its elements.

How to Initialize Vector?

There are three way to initialize vector.

1. Vector V=new Vector();

It is the default way to create vector. It creates an empty vector with the size of 10. The size of vector will grow when it needs 11th items.

2. Vector object= new Vector(int initialCapacity)
Vector vc=new Vector(5);

It will create vector with initial size 5.

3. Vector object= new vector(int initialcapacity, capacityIncrement)
Vector vec= new Vector(4, 6)

It will create vector with size 4 and increment capacity is 6. It means when you add 5th element in the list the size of vector will be increased by 6 and capacity of vector will be 10.

Different Between ArrayList and Vector

ArrayList Vector
It is not Synchronized It is Synchronized
It increments 50% of current array size if number of elements exceeds from its capacity. It increments 100% of current array size. It means it can grow double of ArrayList.
It is not a legacy class. It is legacy class.
It gives faster performance on searching, adding, delete and update because it is not synchronized. It gives poor performance because it is synchronized.
It uses Iterator interface to traverse the element. It uses Enumeration interface to traverse the element. But it can use Iterator also.

Constructors of Vector class

Constructors Descriptions
Vector() Constructs an empty vector so that its internal data array has size 10 and its standard capacity increment is zero.
Vector(Collection<? extends E> c) Constructs a vector containing the elements of the specified collection, in the order they are returned by the collection’s iterator.
Vector(int initialCapacity) Constructs an empty vector with the specified initial capacity and with its capacity increment equal to zero.
Vector(int initialCapacity, int capacityIncrement) Constructs an empty vector with the specified initial capacity and capacity increment.

Methods of Vector Class

Methods Descriptions
boolean add(E e) Append the element at the end of the list.
void add(int index, E element) Insert the element at the specified position in the list.
boolean addAll(
Collection<? extends E> c)
Append entire element from one collection to the end of the list. The orders are defined as the iterator returns value.
boolean addAll(
int index, Collection<? extends E> c)
Insert entire elements from one collection to list at the specified postion.
void addElement(E obj) Adds the specified component to the end of this vector, increasing its size by one.
int capacity() Returns the current capacity of this vector.
void clear() Clear the list by removing all the items.
Object clone() Make a clone of arraylist.
boolean contains(Object o) returns true if arraylist contains specified items.
boolean containsAll(Collection<?> c) Returns true if this Vector contains all of the elements in the specified Collection.
void copyInto(Object[] anArray) Copies the components of this vector into the specified array.
E elementAt(int index) Returns the component at the specified index.
Enumeration elements() Returns an enumeration of the components of this vector.
void ensureCapacity(int minCapacity) Increase the capacity of arraylist.
boolean equals(Object o) Compares the specified Object with this Vector for equality.
E firstElement() Returns the first component (the item at index 0) of this vector.
E get(int index) Returns the element at the specified index position in the list.
int hashCode() Returns the hash code value for this Vector.
int indexOf(Object o) Returns the index of first occurrence of element in the list. If item not found returns -1.
int indexOf(Object o, int index) Returns the index of the first occurrence of the specified element in this vector, searching forwards from index, or returns -1 if the element is not found.
void insertElementAt(E obj, int index) Inserts the specified object as a component in this vector at the specified index.
boolean isEmpty() Returns true if list is empty.
Iterator iterator() Returns an iterator over the elements in this list in proper sequence.
E lastElement() Returns the last component of the vector.
int lastIndexOf(Object o) Returns the index of last occurrence of element in the list. If item not found returns -1.
int lastIndexOf(Object o, int index) Returns the index of the last occurrence of the specified element in this vector, searching backwards from index, or returns -1 if the element is not found.
ListIterator<E> listIterator() Returns a list iterator over the elements in this list (in proper sequence).
ListIterator<E> listIterator(int index) Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list.
E remove(int index) Removes the element at the specified position in this list.
boolean remove(Object o) Removes the first occurrence of the specified element from this list, if it is present.
boolean removeAll(Collection<?> c) Removes from this list all of its elements that are contained in the specified collection.
void removeAllElements() Removes all components from this vector and sets its size to zero.
boolean removeElement(Object obj) Removes the first (lowest-indexed) occurrence of the argument from this vector.
void removeElementAt(int index) Deletes the component at the specified index.
protected void removeRange(
int fromIndex, int toIndex)
Removes from this list all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive.
boolean retainAll(Collection<?> c) Retains only the elements in this list that are contained in the specified collection.
E set(int index, E element) Replaces the element at the specified position in this list with the specified element.
void setElementAt(E obj, int index) Sets the component at the specified index of this vector to be the specified object.
void setSize(int newSize) Sets the size of this vector.
int size() Returns the number of elements in this list.
List subList(int fromIndex, int toIndex) Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.
Object[] toArray() Returns an array containing all of the elements in this list in proper sequence (from first to last element).
<T> T[] toArray(T[] a) Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.
String toString() Returns a string representation of this Vector, containing the String representation of each element.
void trimToSize() Trims the capacity of this ArrayList instance to be the list’s current size.

 

Programming Example

import java.util.*;
class Vector_Class
{
  public static void main(String[] args)
  {
    //Initial size is 2
    Vector v=new Vector(2);
    v.addElement("Laptop");
    v.addElement("Desktop");
    v.addElement("iPhone");
    System.out.println(v);
    System.out.println("Vector Size is "+v.size());
    System.out.println("Default Capacity Increment is "+v.capacity());
    System.out.println("If Contains iPhone : "+v.contains("iPhone"));
    System.out.println("First Element is : "+v.firstElement());
    System.out.println("Last Element is : "+v.lastElement());
    System.out.println("Index Position of Desktop : "+v.indexOf("Desktop"));
    System.out.println("Is Vector Empty ? : " +v.isEmpty());
    //Adding Mobile at index position 2
    v.add(2,"Mobile");
    System.out.println("New List is after adding Mobile : "+v);
    //Removing Desktop
    v.remove("Desktop");
    System.out.println("New List is after removing Desktop : "+v);
    
    //Iterate through Iterator Interface
    System.out.println("Elements are : ");
    Iterator itr=v.iterator();    
    while(itr.hasNext())
    {
      System.out.print(itr.next() + " , ");
    }
    
    //Traverse using Enumertion
    System.out.println("\nElements are : ");
    Enumeration en=v.elements();
    while(en.hasMoreElements())
    {
      System.out.print(en.nextElement() + " , ");
    }    
  }
}


Output

D:\JavaProgram>javac Vector_Class.java

D:\JavaProgram>java Vector_Class
[Laptop, Desktop, iPhone]
Vector Size is 3
Default Capacity Increment is 4
If Contains iPhone : true
First Element is : Laptop
Last Element is : iPhone
Index Position of Desktop : 1
Is Vector Empty ? : false
New List is after adding Mobile : [Laptop, Desktop, Mobile, iPhone]
New List is after removing Desktop : [Laptop, Mobile, iPhone]
Elements are :
Laptop , Mobile , iPhone ,
Elements are :
Laptop , Mobile , iPhone ,
_

Summary

In this chapter you have learned all about Vector class in Java. Vector is like an array list but the difference is that is synchronized and exceeds its capacity size doubly. In the next chapter you will learn Stack Class in Java.


Linked List Class Java with Programming Example

linkedlistIn this chapter you will learn:

  1. What is LinkedList Class in Java?
  2. Methods of Linked List Class
  3. Programming Example
 What is Linked List Class in Java?

Java LinkedList class uses doubly linked list structure to store element in the list. It extends the abstract class and implements List and Deque Interface. Java LinkedList class can contains null value or duplicate value. LinkedList class doesn’t support synchronization. It means if more than one thread is accessing Linked List simultaneously and one thread makes some changes the Linked List must be externally synchronized. Manipulation of Linked List is faster than ArrayList because no shifting needs to be occurred.

Initialization

You can define LinkedList class as follow. You must include java.util.*; in your program.

LinkedList list=new LinkedList();

Constructors of LinkedList class

Constructors Descriptions
LinkedList() This constructor builds an empty linked list.
LnkedList(Collection c) This constructor builds a linked list that is initialized with the elements of the collection c.

Methods of ArrayList Class

Methods Descriptions
boolean add(E e) Append the element at the end of the list.
void add(int index, E element) Insert the element at the specified position in the list.
boolean addAll(
Collection<? extends E> c)
Append entire element from one collection to the end of the list. The orders are defined as the iterator returns value.
boolean addAll(
int index, Collection<? extends E> c)
Insert entire elements from one collection to list at the specified postion.
void clear() Clear the list by removing all the items.
Object clone() Make a clone of arraylist.
boolean contains(Object o) returns true if arraylist contains specified items.
void ensureCapacity(int minCapacity) Increase the capacity of arraylist.
E get(int index) Returns the element at the specified index position in the list.
int indexOf(Object o) Returns the index of first occurrence of element in the list. If item not found returns -1.
boolean isEmpty() Returns true if list is empty.
Iterator iterator() Returns an iterator over the elements in this list in proper sequence.
int lastIndexOf(Object o) Returns the index of last occurrence of element in the list. If item not found returns -1.
ListIterator<E> listIterator() Returns a list iterator over the elements in this list (in proper sequence).
ListIterator<E> listIterator(int index) Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list.
E remove(int index) Removes the element at the specified position in this list.
boolean remove(Object o) Removes the first occurrence of the specified element from this list, if it is present.
boolean removeAll(Collection<?> c) Removes from this list all of its elements that are contained in the specified collection.
protected void removeRange(
int fromIndex, int toIndex)
Removes from this list all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive.
boolean retainAll(Collection<?> c) Retains only the elements in this list that are contained in the specified collection.
E set(int index, E element) Replaces the element at the specified position in this list with the specified element.
int size() Returns the number of elements in this list.
List subList(int fromIndex, int toIndex) Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.
Object[] toArray() Returns an array containing all of the elements in this list in proper sequence (from first to last element).
<T> T[] toArray(T[] a) Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.
void trimToSize() Trims the capacity of this ArrayList instance to be the list’s current size.

 

Programming Example

import java.util.*;

class Linked_List
{
  public static void main(String[] args)
  {
    LinkedList<String> list=new LinkedList<String>();
    list.add("Computer");
    list.add("Mobile");
    list.add("Tablet");
    list.add("iPhone");
    
    //Adding an item at the begining of the list
    list.addFirst("iPad");
    System.out.println(list);
    
    //Adding an item at the last position of the list
    list.addLast("Laptop");
    System.out.println(list);
   
    //Making clone
    Object obj=new Object();
    obj=list.clone();
    System.out.println("Clone : "+obj);
    
    //Remove item at index position 2
    System.out.println("Items Removed : "+list.remove(2));
    
    //Printing Using Iterator
    Iterator<String> itr=list.iterator();
    while(itr.hasNext())
    {
      System.out.print(itr.next()+" , ");
    }
  }
}

Output

D:\JavaProgram>javac Linked_List.java

D:\JavaProgram>java Linked_List
[iPad, Computer, Mobile, Tablet, iPhone]
[iPad, Computer, Mobile, Tablet, iPhone, Laptop]
Clone : [iPad, Computer, Mobile, Tablet, iPhone, Laptop]
Items Removed : Mobile
iPad , Computer , Tablet , iPhone , Laptop ,
_

Summary

In this chapter you have learned what is LInkedList class and their methods in Java with complete programming example. In the next chapter you will learn about Vector Class in Java.


ArrayList Class in Java with Programming Example

ArrayListIn this chapter you will learn:

  1. What is ArrayList class?
  2. Methods of ArrayList class
  3. Programming Example
 What is ArrayList class?

ArrayList is such type of storage array which is dynamic in size and can grow and shrink at runtime. It is actually a resizable array. It implements the list interface and has almost same operations as lists but it doesn’t allow null value.

Initialization

You can define ArrayList class as follow. You must include java.util.*; in your program.

ArrayList alist=new ArrayList();

Constructors of ArrayList class

Constructors Descriptions
ArrayList() This constructor builds an empty arraylist.
ArrayList(Collection c) This constructor builds an array list that is initialized with the elements of the collection c.
ArrayList(int capacity) This constructor builds an array list that has the specified initial capacity. The capacity is the size of the underlying array that is used to store the elements. The capacity grows automatically as elements are added to an array list.

Methods of ArrayList Class
Methods Descriptions
boolean add(E e) Append the element at the end of the list.
void add(int index, E element) Insert the element at the specified position in the list.
boolean addAll(
Collection<? extends E> c)
Append entire element from one collection to the end of the list. The orders are defined as the iterator returns value.
boolean addAll(
int index, Collection<? extends E> c)
Insert entire elements from one collection to list at the specified postion.
void clear() Clear the list by removing all the items.
Object clone() Make a clone of arraylist.
boolean contains(Object o) returns true if arraylist contains specified items.
void ensureCapacity(int minCapacity) Increase the capacity of arraylist.
E get(int index) Returns the element at the specified index position in the list.
int indexOf(Object o) Returns the index of first occurrence of element in the list. If item not found returns -1.
boolean isEmpty() Returns true if list is empty.
Iterator iterator() Returns an iterator over the elements in this list in proper sequence.
int lastIndexOf(Object o) Returns the index of last occurrence of element in the list. If item not found returns -1.
ListIterator<E> listIterator() Returns a list iterator over the elements in this list (in proper sequence).
ListIterator<E> listIterator(int index) Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list.
E remove(int index) Removes the element at the specified position in this list.
boolean remove(Object o) Removes the first occurrence of the specified element from this list, if it is present.
boolean removeAll(Collection<?> c) Removes from this list all of its elements that are contained in the specified collection.
protected void removeRange(
int fromIndex, int toIndex)
Removes from this list all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive.
boolean retainAll(Collection<?> c) Retains only the elements in this list that are contained in the specified collection.
E set(int index, E element) Replaces the element at the specified position in this list with the specified element.
int size() Returns the number of elements in this list.
List subList(int fromIndex, int toIndex) Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.
Object[] toArray() Returns an array containing all of the elements in this list in proper sequence (from first to last element).
<T> T[] toArray(T[] a) Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.
void trimToSize() Trims the capacity of this ArrayList instance to be the list’s current size.

 

Programming Example

import java.util.*;

class Array_List
{
  public static void main(String[] args)
  {
    ArrayList alist=new ArrayList();
    alist.add("Table");
    alist.add("Chair");
    alist.add("Speaker");
    alist.add("Guitar");
    alist.add("Fan");
    
    //Printing arraylist item
    System.out.print("All Array List Items are ");
    System.out.println(alist);
    
    //Adding new item at index position 2
    alist.add(2, "Calculator");
    System.out.println("Adding Calculator : "+alist);
    
    //Removing item Calculator
    alist.remove("Calculator");
    System.out.println("Removing Calculator : "+alist);
    
    //Get element name at specified index position
    System.out.println("Element at Index Position 2 : " + alist.get(2));
    
    //Get total size of arraylist
    System.out.println("ArrayList Size are : " + alist.size());
    
    //Clear the arraylist
    alist.clear();
    System.out.println("After clearing arraylist " + alist);
  }
}

Output

All Array List Items are [Table, Chair, Speaker, Guitar, Fan]
Adding Calculator : [Table, Chair, Calculator, Speaker, Guitar, Fan]
Removing Calculator : [Table, Chair, Speaker, Guitar, Fan]
Element at Index Position 2 : Speaker
ArrayList Size are : 5
After clearing arraylist []
_

Summary

ArrayList is very useful when you don’t know how many items have to be added in the list. It can be shrink and grow dynamically at runtime. This chapter also explains all the methods or ArrayList class with programming example. It is very easy to learn this keyword in this chapter. The next chapter is explaining one more List item LinkedList.


List Interface –Java Collection with Programming Example

Linked ListIn this chapter you will learn:

  1. What is List Interface in Java Collection?
  2. List Interface methods
  3. Iterator and ListIterator Interface
 What is List Interface in Java Collection?

A list is an order collection which stores item at exact position where it is added. It doesn’t change items position so it is also known as sequence object. List allows duplicate entry so it may have duplicate element. There are 2 general purpose list implementations ArrayList andLinkedList. List interface provides following operations on elements.

Java List

  • Positional Access: Each element can be accessed by their index position or numerical position so based on their numerical position it manipulates elements in the list. It includes method such as get(), set(), add(), addall() and remove().
  • Search: Using IndexOf and lastIndexOf method it searches for specified elements in the list and return their numerical position or index number.
  • Iteration: Using listIterator() method traverse lists in a sequential way.
  • Range-view: The sublist() method performs arbitrary range operations on the list.

Initialization

A list can be initialized as follow:

List booklist=new ArrayList();

Methods

Methods Descriptions
void add(int index, object obj) Insert object at specified index position. The preexisting object shifted up
boolean addAll(int index, Collection c) Inserts all elements of c into the invoking lists at the specified index position. The preexisting object shifted up. It returns true if any changes made into the list otherwise returns false.
Object get(int index) Returns the object stored at the specified index position.
int indexOf(Object obj) Returns index position of first instance of object in the list. If object not found it returns -1.
int lastIndexOf(Object obj) Returns index position of last instance of object in the list. If object not found it returns -1.
ListIterator listIterator() Returns an iterator to the start of the invoking list.
ListIterator listIterator(int index) Returns an iterator to the invoking list that begins at the specified index.
Object remove(int index) It removes the object from specified position and returns deleted objects. Subsequent objects index position shifted to left position or decremented by one.
Object set(int index, Object obj) Assigns obj to the location specified by index within the invoking list.
List subList(int start, int end) Returns a set of element ranging from specified start and end position in the invoking list.

Programming Example

import java.util.*;
class List_Example
{
 public static void main(String[] args)
 {
   //Creating ArrayList
   List booklist=new ArrayList();
   
   //Adding Item to list
   booklist.add("Java");
   booklist.add("C#");
   booklist.add("C++");
   booklist.add("SQL");
   booklist.add("Python");
   
   //Printing List
   System.out.println(booklist);
   
   //Adding new item at index position 3
   booklist.add(3, "PHP");
   //Printing List
   System.out.println(booklist);
   
   //Getting index position of object SQL
   System.out.println(booklist.indexOf("SQL"));
   
   //Removing Object stored at index position 2
   System.out.println(booklist.remove(2));
   
   //Getting a sublist of object ranging from 2 to 4
   System.out.println(booklist.subList(2,4));
 }
}

Output

[Java, C#, C++, SQL, Python]
[Java, C#, C++, PHP, SQL, Python]
4
C++
[PHP, SQL]
_

Iterator

iterator is an object that implements either Iterator or ListIterator Interface. IteratorInterface allows you to traverse through collections obtaining or removing elements. TheListIterator Interface extends the Iterator and allows you to traverse collection in both direction forward and backward.

Methods and Description of ListIterator

Methods Descriptions
add(E e) It add element in the list at specified position.
hasNext() This method returns true if iterator finds next element in the list while traversing forward direction.
hasPrevious() It returns true if iterator finds next element in the list while traversing backward direction.
next() It returns next element of the list and shift cursor to next position.
nextIndex() Returns the index of the element that would be returned by a subsequent call to next().
previous() Returns the previous elements in the list and shift cursor position backwards.
previousIndex() Returns the index of the element that would be returned by a subsequent call to previous().
remove() Removes element from the list.
set(E e) Replaces the last element returned by next() or previous() with the specified element.

Above is the list of methods that is used while traversing lists using iterators. You can understand its working style more clearly using following programming example.

Programming Example

import java.util.*;
class List_Iterator
{
 public static void main(String[] args)
 {
   //Creating ArrayList
   List booklist=new ArrayList();
   
   //Adding Item to list
   booklist.add("Java");
   booklist.add("C#");
   booklist.add("C++");
   booklist.add("SQL");
   booklist.add("Python");
   
   //Printing List
   System.out.println(booklist);
   
   //Using ListIterator
   //hasNext() Method
   System.out.print("Printing Forward Direction : ");
   ListIterator Ltr=booklist.listIterator();
   while(Ltr.hasNext())
   {
     Object element=Ltr.next();     
     System.out.print(element + " , ");
   }
   System.out.println();
   
   //hasPrevious() Method
   System.out.print("Printing Backward Direction : ");
   while(Ltr.hasPrevious())
   {
     Object element=Ltr.previous();
     System.out.print(element + " , ");
   }
   System.out.println();
 }
}

Output

[Java, C#, C++, SQL, Python]
Printing Forward Direction : Java , C# , C++ , SQL , Python ,
Printing Backward Direction : Python , SQL , C++ , C# , Java ,
_

Summary

In this chapter you have learned how to use List Interface in java collection. You have also learned how to use Iterator and ListIterator Interface to traverse through list. Programming examples help you to understand topic more clearly. In the next chapter you will learn ArrayList class in Java.


Complete Collection Framework in Java with Programming Example

Java CollectionsIn this chapter you will learn:

  1. What is Collection in Java?
  2. Java Collection Structure
  3. List Interface
  4. Queue Interface
  5. Set Interface
  6. Map Interface
 What is Collection in Java?

Before starting this tutorial you must need to know what Collection in Java is and how to use it in programming. You also need to know the benefit of collection. A collection is like an array which stores collection of data but there is huge difference between them. An array size is fixed and it is defined while initialized array but the size of collection objects is dynamic and can be grow or shrink at run time. There is also various usage of Collection object that is mentioned below:

  1. Collection support more flexible data structure than array.
  2. The complexity of Collection framework is encapsulated and you are provided several methods and properties to work with them. For example for adding any new element there is add() method. So, it simplifies your code and gives better access to collection element than array.
  3. It reduces your development effort by providing rich set of classes.
  4. It gives you robust code quality because it is tested by several high qualified programmers.

Structure of Collection

Java Collections

You will learn all the classes and interfaces of collections in next few chapters. All the classes are explained with complete programming examples.

List Interface

A list is an order collections or sequence of items. You can insert, delete or search items based on index position. It also allows duplicate entry in the list collections.

1. ArrayList
2. LinkedList
3. Vector
4. Stack

Queue Interface

A Queue is based on First in First Out formulae. This collection is designed for holding elements prior to processing. Apart from basic collection operations it provides additional insertion, extraction and inspection operations.

1. PriorityQueue
2. Deque
3. ArrayDeque

Set Interface

Unlike List Interface Set doesn’t allow adding duplicate values in collection. It contains method only inherited from collections and prohibited duplicate entries.

1. HashSet
2. LinkedHashSet
3. SortedSet
4. TreeSet

Map Interface

A Map is an object that maps keys to values. It contains unique keys for all the elements and that elements can be accessed later using keys value. A map cannot contain duplicate keys.

1. Hashtable
2. LinkedHashMap
3. HashMap
4. TreeMap

Iterator and ListIterator

Iterator and ListIterator both are used for traversing collections still there are some differences between Iterator and ListIterator. Iterator and listiterator is very useful and we will use it widely in collection programming.

Summary

It is only overview of collections framework. We have kept this topic short and useful but all the interfaces are explained in details in separate chapter. So, let’s start with List Interface