Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
13 views

Java Collections

A Java collection framework provides an architecture to store and manipulate a group of objects.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Java Collections

A Java collection framework provides an architecture to store and manipulate a group of objects.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 32

Java Collections

Framework
Topics
• What is a Java collection framework?
• Why use Java collection?
• Java collection framework Hierarchy
• Interface
• List
• Queue
• Sets
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.
Why use Java collection?

The Java collection framework provides the developers to access


prepackaged data structures as well as algorithms to manipulate data.
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
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.
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
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 ();
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 specified element, or
int lastIndexOf(Object o) -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.

void trimToSize() Trims the capacity of this ArrayList instance to be the list’s current size.
import java.util.ArrayList;
public class Main{
public static void main(String[] args) {
ArrayList<String> list1= new ArrayList<String>();
ArrayList list2= new ArrayList();
list1.add("Arun");
list1.add("john");
list1.add("Joe");
list1.add("Joe");
list2.add("Jac");
list2.add(2.2);
list2.add(56);
System.out.println(list1);
System.out.println(list2);
for (int i=0;i<list1.size();i++)
System.out.println(list1.get(i));
for(String ele : list1)
System.out.println(ele);
Iterator itr= list1.iterator();
while(itr.hasNext())
System.out.println(itr.next);
list2.remove("Jac");
System.out.println(list2);
list2.clear();
System.out.println(list2);
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:
Doubly Linked List:
Methods in the linked list are listed below:

Method Description

boolean add( Object o) It is used to append the specified element to the end of the vector.

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

void add (int index, Object element) Inserts the element at the specified element in the vector.

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

boolean remove(Object o) Removes the first occurrence of the specified element from this list.

int indexOf(Object element) Returns the index of the first occurrence of the specified element in this list, or -1.

int lastIndexOf(Object element) Returns the index of the last occurrence of the specified element in this list, or -1.
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());
}
}
}
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);
Method Description

boolean add(Object o) Appends the specified element to the end of the list.

void clear() Removes all of the elements from this list.

void add(int index, Object


Inserts the specified element at the specified position.
element)

boolean remove(Object o) Removes the first occurrence of the specified element from this list.

boolean contains(Object
Returns true if this list contains the specified element.
element)

int
indexOfObject (Object eleme Returns the index of the first occurrence of the specified element in the list, or -1.
nt)

int size() Returns the number of elements in this list.

Return the index of the last occurrence of the specified element in the list, or -1 if the list does not contain any
int lastIndexOf(Object o)
element.
System.out.println("Size is: "+vec.size());
System.out.println("Default capacity is: "+vec.capacity());
//Display Vector elements
System.out.println("Vector element is: "+vec);
vec.addElement("Rat");
vec.addElement("Cat");
vec.addElement("Deer");
//Again check size and capacity after two insertions
System.out.println("Size after addition: "+vec.size());
System.out.println("Capacity after addition is: "+vec.capacity());
//Display Vector elements again
System.out.println("Elements are: "+vec);
//Checking if Tiger is present or not in this vector
if(vec.contains("Tiger"))
{
System.out.println("Tiger is present at the index " +vec.indexOf("Tiger"));
}
else
{
System.out.println("Tiger is not present in the list.");
}
//Get the first element
System.out.println("The first animal of the vector is = "+vec.firstElement());
//Get the last element
System.out.println("The last animal of the vector is = "+vec.lastElement());
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.
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.
Method Description
Inserts the specified element into the queue
boolean add(object)
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,


Object poll()
or returns null if the queue is empty.

Retrieves, but does not remove the head of


Object element()
the queue.

Retrieves, but does not remove the head of


Object peek() this queue, or returns null if the queue is
empty.
import java.util.*;
class QueueExample {
public static void main(String args[]){
PriorityQueue<String> queue=new PriorityQueue<String>(); // creating priority queue
queue.add("Amit"); // adding elements
queue.add("Rachit");
queue.add("Rahul");
System.out.println("head:"+queue.element());
System.out.println("head:"+queue.peek());
head:Amit
System.out.println("iterating the queue elements:"); head:Amit
Iterator itr=queue.iterator();
while(itr.hasNext()){
iterating the queue
System.out.println(itr.next()); elements:
}
Amit Rachit Rahul
queue.remove();
queue.poll(); after removing two
System.out.println("after removing two elements:");
elements: Rahul
Iterator<String> itr2=queue.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
}
}
Sets

A Set refers to a collection that cannot contain duplicate elements. It is


mainly used to model the mathematical set abstraction. Set has its
implementation in various classes such as HashSet, TreeSet and
LinkedHashSet.
HashSet:
Java HashSet class creates a collection that use a hash table for
storage. Hashset only contain unique elements and it inherits the
AbstractSet class and implements Set interface. Also, it uses a
mechanism hashing to store the elements.
Method Description
boolean add(Object
Adds the specified element to this set if it is not already present.
o)
boolean
Returns true if the set contains the specified element.
contains(Object o)
void clear() Removes all the elements from the set.
boolean isEmpty() Returns true if the set contains no elements.
boolean
Remove the specified element from the set.
remove(Object o)
Returns a shallow copy of the HashSet instance: the elements
Object clone()
themselves are not cloned.
Iterator iterator() Returns an iterator over the elements in this set.
int size() Return the number of elements in the set.
import java.util.*;
class HashsetExample{
public static void main(String args[]){

HashSet<String>=new HashSet(); // creating hashSet


al.add("Rachit"); // adding elements
The output of the above code
al.add("Amit");
would be:
al.add("jack");
Amit
Iterator<String&amp;amp;gt; itr=al.iterator(); Rachit
while(itr.hasNext()){ Jack
System.out.println(itr.next());
}
}
}
Linked Hashset
Java LinkedHashSet class is a Hash table and Linked list implementation
of the set interface. It contains only unique elements like HashSet.
Linked HashSet also provides all optional set operations and maintains
insertion order.
TreeSet :
import java.util.*;
TreeSet class implements the Set class TreeSetExample{
interface that uses a tree for public static void main(String args[]){
TreeSet<String>al=new TreeSet<String>(); // creating
storage. The objects of this class treeSet
are stored in the ascending order. al.add("John"); // adding elements
al.add("Sam");
Also, it inherits AbstractSet class al.add("Rick");
and implements NavigableSet Iterator&amp;amp;lt;String&amp;amp;gt; itr=al.iterator();
interface. It contains only unique while(itr.hasNext()){
System.out.println(itr.next());
elements like HashSet. In }
TreeSet class, access and retrieval }
}
time are faster.
Map Interface

• A map contains values on the basis of key, i.e. key and value pair. Each
key and value pair is known as an entry. A Map contains unique keys.

Class Description
HashMap HashMap is the implementation of Map, but it doesn't maintain
any order.
LinkedHashMap LinkedHashMap is the implementation of Map. It inherits
HashMap class. It maintains insertion order.
TreeMap TreeMap is the implementation of Map and SortedMap. It
maintains ascending order.

You might also like