0% found this document useful (0 votes)
4 views12 pages

Unit 4 Notes.docx

Uploaded by

ayuu19628
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views12 pages

Unit 4 Notes.docx

Uploaded by

ayuu19628
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Unit-4 java collection framework

java Collection:-

java Collection means a single unit of objects. Java Collection framework provides many interfaces
(Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet,
LinkedHashSet, TreeSet).

It provides readymade architecture.


o​ It represents a set of classes and interfaces.
o​ It is optional.

the java.util package contains all the classes and interfaces for the Collection framework.

Iterator 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 interface provides the facility of iterating the elements in a forward direction only.
Methods of Iterator interface
There are only three methods in the Iterator interface. They are:

List Interface
List interface is the child interface of Collection interface. It inhibits a list type data structure
in which we can store the ordered collection of objects. It can have duplicate values.
List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
List <data-type> list1= new ArrayList();
List <data-type> list2 = new LinkedList();
List <data-type> list3 = new Vector();
List <data-type> list4 = new Stack();

Array List:-
The Array List class implements the List interface. It uses a dynamic array to store the
duplicate element of different data types.
import java.util.*;
class TestJavaCollection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next()); } } }

Operations using ArrayList:


1)​ To add an element
2)​ To remove an element
3)​ To update
4)​ To reverse an array
5)​ Append

LinkedList:-

LinkedList implements the Collection interface. It uses a doubly linked list internally
to store the elements. It can store the duplicate elements. It maintains the insertion
order and is not synchronized. In LinkedList, the manipulation is fast because no
shifting is required.
Example:-
import java.util.*;
public class TestJavaCollection2{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while (itr.hasNext()){
System.out.println(itr.next ());
} }}

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.

import java.util.*;
public class TestJavaCollection3{
public static void main(String args[]){
Vector<String> v=new Vector<String>();
v.add("Ayush");
v.add("Amit");
v.add("Ashish");
v.add("Garima");
Iterator<String> itr=v.iterator();
while(itr.hasNext()){
System.out.println(itr.next()); } }
}

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.
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());
} } }

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<String> q1 = new PriorityQueue();


Queue<String> q2 = new ArrayDeque();

Set Interface:-

Set Interface in Java is present in java.util package. It extends the Collection interface. It
represents the unordered set of elements which doesn't allow us to store the duplicate items.
We can store at most one null value in Set. Set is implemented by HashSet, LinkedHashSet,
and TreeSet.
Set<data-type> s1 = new HashSet<data-type>();
Set<data-type> s2 = new LinkedHashSet<data-type>();
Set<data-type> s3 = new TreeSet<data-type>();

HashSet:-
HashSet class implements Set Interface. It represents the collection that uses a hash
table for storage. Hashing is used to store the elements in the HashSet. It contains
unique items.
import java.util.*;
public class TestJavaCollection7{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next()); } }
}

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.

Example :-
import java.util.*;
public class TestJavaCollection8{
public static void main(String args[]){
LinkedHashSet<String> set=new LinkedHashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next()); } }
}

SortedSet Interface:-

SortedSet is the alternate of Set interface that provides a total ordering on its elements. The
elements of the SortedSet are arranged in the increasing (ascending) order. The SortedSet
provides the additional methods that inhibit the natural ordering of the elements.

SortedSet<data-type> set = new TreeSet();

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.

import java.util.*;
public class TestJavaCollection9{
public static void main(String args[]){
//Creating and adding elements
TreeSet<String> set=new TreeSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }

Features HashSet LinkedHashSet TreeSet

HashSet internally LinkedHashSet uses


Internal TreeSet uses TreeMap
uses HashMap for LinkedHashMap
Working internally to store objects
storing objects internally to store objects

If you don’t want to If you want to maintain If you want to sort the
When To maintain insertion the insertion order of elements according to some
Use order but want to elements then you can Comparator then use
store unique objects use LinkedHashSet TreeSet
Features HashSet LinkedHashSet TreeSet

While TreeSet orders the


elements according to
HashSet does not LinkedHashSet maintains
supplied Comparator. By
Order maintain insertion the insertion order of
default, objects will be
order objects
placed according to their
natural ascending order.

HashSet gives O(1) LinkedHashSet gives While TreeSet gives the


Complexity complexity for insertion, removing, and performance of order
of insertion, removing, retrieving operations O(log(n)) for insertion,
Operations and retrieving performance in order removing, and retrieving
objects O(1). operations.

The performance of
LinkedHashSet is slower TreeSet performance is
The performance of than TreeSet. It is almost better than LinkedHashSet
HashSet is better similar to HashSet but except for insertion and
Performance when compared to slower because removal operations because
LinkedHashSet and LinkedHashSet internally it has to sort the elements
TreeSet. maintains LinkedList to after each insertion and
maintain the insertion removal operation.
order of elements

HashSet uses
LinkedHashSet uses
equals() and TreeSet uses compare() and
equals() and hashCode()
Compare hashCode() methods compareTo() methods to
methods to compare it’s
to compare the compare the objects
objects
objects

TreeSet does not permit null


Null HashSet allows only LinkedHashSet allows value. If you insert null value
Elements one null value. only one null value. into TreeSet, it will throw
NullPointerException.

HashSet obj = new LinkedHashSet obj = new


Syntax TreeSet obj = new TreeSet();
HashSet(); LinkedHashSet();
Java 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.

there are two interfaces for implementing Map in java: Map and SortedMap, and three
classes: HashMap, LinkedHashMap, and TreeMap.
A Map doesn't allow duplicate keys, but you can have duplicate values. HashMap and
LinkedHashMap allow null keys and values, but TreeMap doesn't allow any null key or
value.
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.
Java Hashtable class:-

Java Hashtable class implements a hashtable, which maps keys to values. It inherits
Dictionary class and implements the Map interface.
o​ A Hash table is an array of a list. Each list is known as a bucket. The position of the
bucket is identified by calling the hashcode() method. A Hash table contains values
based on the key.
o​ Java Hash table class contains unique elements.
o​ Java Hash table class doesn't allow null key or value.

Hashtable

class Parameters

K: It is the type of keys maintained by this map.


V: It is the type of mapped values.
Example:-
import java.util.*;
class Hashtable1{
public static void main(String args[]){
Hashtable<Integer,String> hm=new Hashtable<Integer,String>();
hm.put(100,"Amit");
hm.put(102,"Ravi");
hm.put(101,"Vijay");
hm.put(103,"Rahul");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}

Sorting in Collection

Method of Collections class for sorting List elements


public void sort(List list): is used to sort the elements of List.

Java Comparable interface


Java Comparable interface is used to order the objects of the user-defined class.
This interface is found in java.lang package and contains only one method named
compareTo(Object).
It provides a single sorting sequence only, i.e., you can sort the elements on the basis of
single data member only.
For example, it may be rollno, name, age or anything else.

compareTo(Object obj) method


public int compareTo(Object obj): It is used to compare the current object with the
specified object.
Java Comparator interface is used to order the objects of a user-defined class.
This interface is found in java.util package and contains 2 methods compare(Object
obj1,Object obj2) and equals(Object element).
It provides multiple sorting sequences, i.e., you can sort the elements on the basis
of any data member, for example, rollno, name, age or anything else.

Properties class in Java:-

The properties object contains key and value pair both as a string. The java.util.Properties
class is the subclass of Hash table.
It can be used to get property value based on the property key. The Properties class provides
methods to get data from the properties file and store data into the properties file. Moreover,
it can be used to get the properties of a system.
Advantage of the properties file
Recompilation is not required if the information is changed from a properties file: If any
information is changed from the properties file, you don't need to recompile the java class. It
is used to store information which is to be changed frequently.
Example :-

import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args)throws Exception{ FileReader reader=new FileRe
ader("db.properties");

Properties p=new Properties();


p.load(reader);

System.out.println(p.getProperty("user"));
System.out.println(p.getProperty("password"));
}
}

Queue :

●​ It maintains FIFO order and implements Queue interface


●​ It holds the elements which are to be processed by their
priorities -> PriorityQueue
●​ Deque, ArrayDeque
●​ Naturalpriority : smallest to largest
●​ Dictionary order (A ---- Z)

Import java.util.Queue;

●​ PriorityQueue<String> q1 = new PriorityQueue<String>();

Set Interface:
●​ A = {1,2,3,4,5,6,7,8,9}
●​ It is present in util package:
●​ import java.util.*;
●​ it represents the unordered collection of objects/elements.
●​ Duplicate elements are not allowed in a set.
●​ Set is implemented by using the following:
●​ HashSet,
●​ HashSet<data-type> hs1 = new HashSet<data-type>();
●​ LinkedHashSet
●​ LinkedHashSet<data-type> lhs1 = new
LinkedHashSet<data-type>();
●​ SortedSet
●​ TreeSet
●​ TreeSet<data-type> ts1 = new TreeSet<data-type>();

HashSet:

●​ Implements Set interface


●​ It represents the collection that uses hash table for storage.
●​ Contains unique items/elements
●​ It does not preserve any order

LinkedHashSet:

●​ It represents the LinkedList implementation of Set interface


●​ It extends the HashSet class and implements Set Interface
●​ It also contains unique elements
●​ It maintains the insertion order and permits null elements

TreeSet:

●​ It implements the SortedSet interface,


●​ It maintains the ascending order.

Java Map Interface:


It contains the values on the basis of keys. (key-value pair)

A map contains unique key but can contain duplicate values

You might also like