0% found this document useful (0 votes)
76 views18 pages

Collection in Java

This document discusses Java collections and the Java Collection Framework. It defines Java collections as a way to represent a group of objects as a single unit that allows operations like searching, sorting, insertion, etc. It then explains that the Java Collection Framework provides interfaces, classes, and algorithms to store and manipulate groups of objects. It discusses the key interfaces like Collection and Iterator, and classes that implement these interfaces like ArrayList, LinkedList, and others. It provides examples of how to use ArrayList and LinkedList in Java code.

Uploaded by

Akshay Khanke
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
76 views18 pages

Collection in Java

This document discusses Java collections and the Java Collection Framework. It defines Java collections as a way to represent a group of objects as a single unit that allows operations like searching, sorting, insertion, etc. It then explains that the Java Collection Framework provides interfaces, classes, and algorithms to store and manipulate groups of objects. It discusses the key interfaces like Collection and Iterator, and classes that implement these interfaces like ArrayList, LinkedList, and others. It provides examples of how to use ArrayList and LinkedList in Java code.

Uploaded by

Akshay Khanke
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 18

What are Java collections?

Java collections refer to a collection of individual objects that are represented as a single
unit. You can perform all operations such as searching, sorting, insertion, manipulation,
deletion, etc., on Java collections just like you do it on data.

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

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.
So why do you think we need Java collections? The Java collection framework provides the
developers to access pre-packaged data structures as well as algorithms to manipulate data.

Why use Java collection?


There are several benefits of using Java collections such as:
 Reducing the effort required to write the code by providing useful data structures
and algorithms
 Java collections provide high-performance and high-quality data structures and
algorithms thereby increasing the speed and quality
 Unrelated APIs can pass collection interfaces back and forth
 Decreases extra effort required to learn, use, and design new API’s
 Supports reusability of standard data structures and algorithms

Java Collection Framework Hierarchy


As we have learned Java collection framework includes interfaces and classes.
Now, let us see the Java collections framework hierarchy.

In the above image, blue part refers to the different interfaces and the yellow
part defines the class. Now, let us understand these components in detail.
Collection Interface:
The Collection interface is the interface which is implemented by all the classes in the
collection framework. It declares the methods that every collection will have. In other
words, we can say that the Collection interface builds the foundation on which the
collection framework depends.

Methods of the Collection Interface

This interface contains various methods which can be directly used by all the collections
which implement this interface. They are:

Method Description

add(Object) This method is used to add an object to the collection.

This method adds all the elements in the given collection to this
addAll(Collection c) collection.

clear() This method removes all of the elements from this collection.

contains(Object o) This method returns true if the collection contains the specified element.

containsAll(Collection This method returns true if the collection contains all of the elements in
c) the given collection.

This method compares the specified object with this collection for
equals(Object o) equality.

hashCode() This method is used to return the hash code value for this collection.

isEmpty() This method returns true if this collection contains no elements.

iterator() This method returns an iterator over the elements in this collection.

max() This method is used to return the maximum value present in the
collection.

This method is used to remove the given object from the collection. If
there are duplicate values, then this method removes the first occurrence
remove(Object o) of the object.
Method Description

removeAll(Collection This method is used to remove all the objects mentioned in the given
c) collection from the collection.

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

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

This method is used to return an array containing all of the elements in


toArray() this collection.

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:
1. public boolean hasNext() – This method returns true if the 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() – 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:

Iterable Interface
The Iterable interface is the root interface for all the collection classes. The Collection
interface extends the Iterable interface and therefore all the subclasses of Collection
interface also implement the Iterable interface.

It contains only one abstract method. i.e.,

Iterator<T> iterator()

It returns the iterator over the elements of type T.


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:
1. ArrayList
2. LinkedList
3. Vectors

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.

Syntax:
ArrayList object = new ArrayList ();

Some of the methods in array list are listed below:


Method Description
boolean add(Collection c) Appends the specified element to the end of a list.
void add(int index, Object
Inserts the specified element at the specified position.
element)
void clear() Removes all the elements from this list.
Return the index in this list of the last occurrence of the
int lastIndexOf(Object o) specified element, or -1 if the list does not contain this
element.
Object clone() Return a shallow copy of an ArrayList.
Object[] toArray() Returns an array containing all the elements in the list.

Trims the capacity of this ArrayList instance to be the list’s


void trimToSize()
current size.

ArrayList example:
import java.util.*;
class ArrayListExample
{
public static void main(String args[])
{
ArrayList al=new ArrayList(); // creating array list
al.add("Jack"); // adding elements
al.add("Tyler");
Iterator itr=al.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
In the above code, it will return the names that we have added using add() method i.e:
Jack
Tyler

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.

Some of the methods in the linked list are listed below:


Method Description
It is used to append the specified element to the end of the
boolean add( Object o)
List.
boolean contains(Object o) Returns true if this list contains the specified element.
void add (int index, Object
Inserts the element at the specified element in the List.
element)
void addFirst(Object o) It is used to insert the given element at the beginning.
void addLast(Object o) It is used to append the given element to the end.
int size() It is used to return the number of elements in a list
Removes the first occurrence of the specified element from
boolean remove(Object o)
this list.
Returns the index of the first occurrence of the specified
int indexOf(Object element)
element in this list, or -1.
int lastIndexOf(Object Returns the index of the last occurrence of the specified
element) element in this list, or -1.

LinkedList example:
import java.util.*;
public class LinkedlistExample
{
public static void main(String args[])
{
LinkedList<String> al=new LinkedList<String>();// creating linked list
al.add("Rachit"); // adding elements
al.add("Rahul");
al.add("Rajat");
Iterator<String> itr = al.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
The output of the above program would be:
Rachit
Rahul
Rajat
Vectors: Vectors are similar to arrays, where the elements of the vector object can be
accessed via an index into the vector. Vector implements a dynamic array. Also, the vector is
not limited to a specific size, it can shrink or grow automatically whenever required. It is
similar to ArrayList, but with two differences :
 Vector is synchronized.
 Vector contains many legacy methods that are not part of the collections framework.

Syntax:
Vector object = new Vector(size, increment);
Below are some of the methods of the Vector class:

Method Description
add(E e) For appending the given element e in the given vector.

add(int index, E e) For inserting the given element, e, at the given index.
For appending all the elements from collection c to the java
addAll(Collection c)
vector.
addAll(int index, Collection For inserting all the elements present in the given collection c to
c) the given java vector at the given index.
capacity() For getting the length of the actual array inside the vector.

clear() For removing all of the elements from the given vector in java.

clone() For making a clone of the given vector in java.


For finding if the given vector contains the specified element. It
contains(Object o)
return true if element is found.
elementAt(int index) For accessing the element at the given index.

firstElement() For getting the first object of the vector present at index 0.
For getting the element at the given index from the Vector in
get(int index)
java.
Method Description
For finding out the index of the first occurrence of the specified
indexOf(Object o) element in this java vector. Keep in mind, if the element is not
present, it will return -1.
insertElementAt(E element,
For inserting the given element at the index in this java vector.
int index)
isEmpty() For finding if the vector in java has any elements in it or not.

lastElement() For getting the last element.


For finding the last occurrence of the given element and its
lastIndexOf(Object o, int
corresponding index. It searches in reverse order and returns -1
index)
if the element is not found in the vector.
remove(int index) For removing the element at the given position.
For removing the first occurrence of the given element in this
remove(Object o)
vector.
For removing all the elements from the Vector that are present
removeAll(Collection<?> c)
in the given Collection.
For removing all the elements from this vector in java and set its
removeAllElements()
size to zero.
For removing the first occurrence (going from the index 0) of
removeElement(Object obj)
the object from the vector.
For deleting the element at the given index from the vector in
removeElementAt(int index)
java.
removeRange(int For removing all the elements from this vector whose index is
fromIndex, int toIndex) between fromIndex, (inclusive), and toIndex, (exclusive).
setSize(int newSize) For setting the size of the given java vector to the size given.

size() For getting the number of elements in the java vector.


For getting an array containing all of the elements in this java
toArray()
vector.
For getting an array with all of the elements in this vector in the
toArray(T[] a) correct order. Here the runtime type of the returned array is
that of the specified array.
For getting a string representation of this Vector in Java,
toString()
containing the String representation of each element.
For making the capacity of the vector in java to be equal to the
trimToSize()
vector’s current size.

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.
The stack data structure has the two most important operations that are push and pop. The
push operation inserts an element into the stack and pop operation removes an element
from the top of the stack. Let's see how they work on stack.

Method Method Description

boolean empty() The method checks the stack is empty or not.

E push(E item) The method pushes (insert) an element onto the top of the
stack.

E pop() The method removes an element from the top of the stack
and returns the same element as the value of that function.

E peek() The method looks at the top element of the stack without
removing it.

int search(Object The method searches the specified object and returns the
o) position of the object.

Consider the following example.

import java.util.*;
public class TestJavaCollection4
{
public static void main(String args[])
{
Stack<String> stack = new Stack<String>();
stack.push("Ayush");
stack.push("Garvit");
stack.push("Amit");
stack.push("Ashish");
stack.push("Garima");
stack.pop();
Iterator<String> itr=stack.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}

Sets
A set is an unordered collection of objects in which duplicate values cannot be stored. This
collection is used when we wish to avoid the duplication of the objects and wish to store
only the unique objects. This set interface is implemented by various classes
like HashSet, TreeSet, LinkedHashSet, etc. Since all the subclasses implement the set, we
can instantiate a set object with any of these classes. For example,
Set<T> hs = new HashSet<> ();
Set<T> lhs = new LinkedHashSet<> ();
Set<T> ts = new TreeSet<> ();

Where T is the type of the object.

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.
Below are some of the methods of Java HashSet class:

Method Description

boolean add(Object o) Adds the specified element to this set if it is not already present.

boolean contains(Object o) Returns true if the set contains the specified element.

void clear() Removes all the elements from the set.

boolean isEmpty() Returns true if the set contains no elements.

boolean remove(Object o) Remove the specified element from the set.

Returns a shallow copy of the HashSet instance: the elements themselves are
Object clone()
not cloned.

Iterator iterator() Returns an iterator over the elements in this set.

int size() Return the number of elements in the set.

Hashset Example:
import java.util.*;
class HashsetExample
{
public static void main(String args[])
{
HashSet <String> al=new HashSet <String>(); // creating hashSet
al.add("Rachit"); // adding elements
al.add("Amit");
al.add("jack");
Iterator <String> itr=al.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
The output of the above code would be:
Amit
Rachit
jack

Linked Hashset :
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.
A LinkedHashSet is very similar to a HashSet. The difference is that this uses a doubly linked
list to store the data and retains the ordering of the elements.

Hashset with a programmatic example:


import java.util.*;
class LinkedHashsetExample
{
public static void main(String args[])
{
LinkedHashSet <String> al=new LinkedHashSet <String>(); // creating linkedhashset
al.add("Mariana"); // adding elements
al.add("Rick");
al.add("Sam");
Iterator <String>itr=al.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
The output of the above code would be:
Mariana
Rick
Sam

TreeSet : TreeSet class implements the Set interface that uses a tree for storage. The objects
of this class are stored in the ascending order. Also, it inherits AbstractSet class and
implements NavigableSet interface. It contains only unique elements like HashSet. In
TreeSet class, access and retrieval time are faster.
Below are some of the methods of Java TreeSet class:
Method Description
boolean addAll(Collection c) Add all the elements in the specified collection to this set.
boolean contains(Object o) Returns true if the set contains the specified element.
boolean isEmpty() Returns true if this set contains no elements.
boolean remove(Object o) Remove the specified element from the set.
void add(Object o) Add the specified element to the set.
void clear() Removes all the elements from the set.
Object clone() Return a shallow copy of this TreeSet instance.
Object first() Return the first element currently in the sorted set.
Object last() Return the last element currently in the sorted set.
int size() Return the number of elements in the set.

TreeSet example:
import java.util.*;
class TreeSetExample{
public static void main(String args[]){
TreeSet <String> al=new TreeSet <String>(); // creating treeSet
al.add("John"); // adding elements
al.add("Sam");
al.add("Rick");
Iterator <String> itr=al.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
The output of the above program would be:
John
Rick
Sam

Now you must be wondering what is the difference between all these sets?
HashSet stores elements in random order whereas LinkedHashSet stores elements according
to insertion order and TreeHashSet stores according to natural ordering.
Java collections: Queue
Queue in Java follows a FIFO approach i.e. it orders the elements in First In First Out manner.
In a queue, the first element is removed first and last element is removed in the end. Each
basic method exists in two forms: one throws an exception if the operation fails, the other
returns a special value.

Also, priority queue implements Queue interface. The elements of the priority queue are
ordered according to their natural ordering, or by a Comparator provided at the queue
construction time. The head of this queue is the least element with respect to the specified
ordering.
Below are some of the methods of Java Queue interface:
Method Description
boolean add(object) Inserts the specified element into the queue and returns true if it is a success.
boolean offer(object) Inserts the specified element into this queue.
Object remove() Retrieves and removes the head of the queue.
Retrieves and removes the head of the queue, or returns null if the queue is
Object poll()
empty.
Object element() Retrieves, but does not remove the head of the queue.
Retrieves, but does not remove the head of this queue, or returns null if the
Object peek()
queue is empty.

Priority queues example:


// Java program to demonstrate the working of
// priority queue in Java
import java.util.*;

class GfG
{
public static void main(String args[])
{
// Creating empty priority queue
PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>();

// Adding items to the pQueue using add()


pQueue.add(10);
pQueue.add(20);
pQueue.add(15);

// Printing the top element of PriorityQueue


System.out.println(pQueue.peek());

// Printing the top element and removing it


// from the PriorityQueue container
System.out.println(pQueue.poll());

// Printing the top element again


System.out.println(pQueue.peek());
}
}

Output:
10
10
15

You might also like