0% found this document useful (0 votes)
10 views55 pages

VIPS OOPS Unit 2 Collection API interface

The document provides an overview of Java Collections, detailing their purpose, implementation, and the Java Collections Framework, which includes various interfaces and classes for data manipulation. It explains key interfaces such as Collection, List, Set, and Map, and highlights differences between data structures like ArrayList, Vector, and LinkedList. Additionally, it covers the use of Iterators, their advantages and disadvantages, and includes examples of how to implement and use these collections in Java.

Uploaded by

manvipaulemail
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)
10 views55 pages

VIPS OOPS Unit 2 Collection API interface

The document provides an overview of Java Collections, detailing their purpose, implementation, and the Java Collections Framework, which includes various interfaces and classes for data manipulation. It explains key interfaces such as Collection, List, Set, and Map, and highlights differences between data structures like ArrayList, Vector, and LinkedList. Additionally, it covers the use of Iterators, their advantages and disadvantages, and includes examples of how to implement and use these collections in Java.

Uploaded by

manvipaulemail
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/ 55

Course :

Paper Code: AIDS-202,


Faculty : Dr. Shivanka
Assistant Professor
VIPS
What are Java collections?
• Java collections refer to a
collection of individual objects
that are represented as a single
u n i t . Yo u c a n p e r f o r m a l l
operations such as searching,
sorting, insertion, manipulation,
deletion, etc., on Java collections
just like you do it on data.
• Java collection it is a single
entity object which can store
multiple data.
Collections In Java and How to Implement Them?

• Java Collections are the one-stop solutions for all the


data manipulation jobs such as storing data, searching,
sorting, insertion, deletion, and updating of data. Java
collection responds as a single object, and a Java
Collection Framework provides various Interfaces and
Classes.
What is a Java Collection?
• A Java Collection is a predefined architecture capable
of storing a group of elements and behaving like a
single unit such as an object or a group.
• And now that you’re aware of what exactly is Java
Collections, the next step is understanding the term
Java Collections Framework.
What is the Java Collection Framework?

• Java Collection Framework


repesents the library .It is set of
predefined classes and interfaces
which is used to store multiple
data.
• It contains two parts
• i)java.util.Collection;
• ii)java.util.Map; (map contains
Key value Pair for exp: roll no
and names)
Java Collection Framework
• Java Collection Framework offers the capability to Java Collection to
represent a group of elements in classes and Interfaces.
• Java Collection Framework enables the user to perform various data
manipulation operations like storing data, searching, sorting, insertion,
deletion, and updating of data on the group of elements. Followed by
the Java Collections Framework,Hierarchy of Java collections and
various descendants or classes and interfaces involved in the Java
Collections.
What is the Collection framework in Java?
• Collection Framework is a combination of classes and interface, which
is used to store and manipulate the data in the form of objects. It
provides various classes such as ArrayList, Vector, Stack, and HashSet,
etc. and interfaces such as List, Queue, Set, etc. for this purpose.
QExplain various interfaces used in Collection framework?
• Collection framework implements various interfaces, Collection
interface and Map interface (java.util.Map) are the mainly used
interfaces of Java Collection Framework. List of interfaces of
Collection Framework is given below:
Java Collection Framework Hierarchy

The following image depicts the


Java Collections Hierarchy.
After the Hierarchy of Java
collections; you should also get to
know the various methods applied to
the Collections in Java to perform
the data manipulation operations.
Various interfaces used in Collection
framework
1. Collection interface: Collection (java.util.Collection) is the primary interface, and every collection must
implement this interface.
Syntax:public interface Collection<E>extends Iterable
Where <E> represents that this interface is of Generic type
2. List interface: List interface extends the Collection interface, and it is an ordered collection of objects. It
contains duplicate elements. It also allows random access of elements.
Syntax:public interface List<E> extends Collection<E>
3. Set interface: Set (java.util.Set) interface is a collection which cannot contain duplicate elements. It can only
include inherited methods of Collection interface
Syntax: public interface Set<E> extends Collection<E>
Queue interface: Queue (java.util.Queue) interface defines queue data structure, which stores the elements in
the form FIFO (first in first out).
Syntax:public interface Queue<E> extends Collection<E>
Various interfaces used in Collection
framework
• 4. Dequeue interface: it is a double-ended-queue. It allows the
insertion and removal of elements from both ends. It implants the
properties of both Stack and queue so it can perform LIFO (Last in
first out) stack and FIFO (first in first out) queue, operations.Syntax:
• Syntax
• public interface Dequeue<E> extends Queue<E>

• 5. Map interface: A Map (java.util.Map) represents a key, value pair


storage of elements. Map interface does not implement the Collection
interface. It can only contain a unique key but can have duplicate
elements. There are two interfaces which implement Map in java that
are Map interface and Sorted Map.
What is the difference between ArrayList and
Vector?
ArrayList Vector

ArrayList is not synchronized. Vector is synchronized.

ArrayList is not a legacy class. Vector is a legacy class.

ArrayList increases its size by 50% of the array size. Vector increases its size by doubling the array size.

ArrayList is not ,thread-safe, as it is not synchronized. Vector list is ,thread-safe, as it,s every method is
synchronized.
What is the difference between ArrayList and
LinkedList?
ArrayList LinkedList
ArrayList uses a dynamic array. LinkedList uses a doubly linked list.
ArrayList is not efficient for LinkedList is efficient for manipulation.
manipulation because too much is
required.
ArrayList is better to store and fetch data.
LinkedList is better to manipulate data.
ArrayList provides random access. LinkedList does not provide random
access.
ArrayList takes less memory overhead as LinkedList takes more memory overhead,
it stores only object as it stores the object as well as the
address of that object.
What is the difference between Iterator and
ListIterator?
Iterator ListIterator
The Iterator traverses the elements in the forward ListIterator traverses the elements in backward and
direction only. forward directions both.

2)The Iterator can be used in List, Set, and Queue. ListIterator can be used in List only.

3)The Iterator can only perform remove operation while ListIterator can perform add,removeand set operation
traversing the collection. while traversing the collection.
Java Iterator
• Java Iterator
An Iterator is an object that can be used to loop through collections, like
ArrayList and HashSet. It is called an "iterator" because "iterating" is
the technical term for looping.

• To use an Iterator, you must import it from the java.util package.

• Getting an Iterator
• The iterator() method can be used to get an Iterator for any collection:
Java Iterator and Advantage
How to use Java Iterator? • Advantages of Java Iterator
• When a user needs to use the Java Iterator, then it's • Iterator in Java became very prevalent due to its
compulsory for them to make an instance of the numerous advantages. The advantages of Java
Iterator interface from the collection of objects they Iterator are given as follows -
desire to traverse over. After that, the received Iterator
maintains the trail of the components in the underlying • The user can apply these iterators to any of the
collection to make sure that the user will traverse over classes of the Collection framework.
each of the elements of the collection of objects.
• In Java Iterator, we can use both of the read and
remove operations.
• If the user modifies the underlying collection while • If a user is working with a for loop, they cannot
traversing over an Iterator leading to that collection, modernize(add/remove) the Collection, whereas, if
then the Iterator will typically acknowledge it and will they use the Java Iterator, they can simply update
throw an exception in the next time when the user will the Collection.
attempt to get the next component from the Iterator.
Disadvantages of Java Iterator
Despite the numerous advantages, the Java Iterator has various
disadvantages also. The disadvantages of the Java Iterator are given
• Java Iterator Methods
below -
• The following figure perfectly
displays the class diagram of the
• The Java Iterator only preserves the iteration in the forward
direction. In simple words, the Java Iterator is a uni-directional
Java Iterator interface. It
Iterator. contains a total of four methods
• The replacement and extension of a new component are not that are:
approved by the Java Iterator.
• In CRUD Operations, the Java Iterator does not hold the various
operations like CREATE and UPDATE.
• hasNext()
• In comparison with the Spliterator, Java Iterator does not support
traversing elements in the parallel pattern which implies that Java
Iterator supports only Sequential iteration.
• next()
• In comparison with the Spliterator, Java Iterator does not support • remove()
more reliable execution to traverse the bulk volume of data.
• forEachRemaining()
Java Iterator Methods
• The forEachRemaining() method • E next(): It is similar to hasNext() method. It
also does not accept any parameter. It returns
was added in the Java 8. Let's E, i.e., the next element in the traversal. If the
discuss each method in detail. iteration or collection of objects has no more
elements left to iterate, then it throws the
NoSuchElementException.
• boolean hasNext(): The method • default void remove(): This method also does
not require any parameters. There is no return
does not accept any parameter. It type of this method. The main function of this
returns true if there are more method is to remove the last element returned
by the iterator traversing through the
elements left in the iteration. If underlying collection.
there are no more elements left,
then it will return false.
Java Iterator Methods
• default void
forEachRemaining(Consumer action):
It is the only method of Java Iterator that
takes a parameter. It accepts action as a
parameter. Action is nothing but that is to
be performed. There is no return type of
the method. This method performs the
particularized operation on all of the left
components of the collection until all the
components are consumed or the action
throws an exception. Exceptions thrown
by action are delivered to the caller. If the
action is null, then it throws a
NullPointerException.
Iterator Example
import java.io.*; System.out.println("CityNames elements : ");
import java.util.*;
public class JavaIteratorExample { while (iterator.hasNext())
public static void main(String[] args)
System.out.print(iterator.next() + " ");
{
System.out.println();
ArrayList<String> cityNames = new ArrayList<String>();
}
cityNames.add("Delhi");
}
cityNames.add("Mumbai");
cityNames.add("Kolkata");
cityNames.add("Chandigarh"); Output:
cityNames.add("Noida");
// Iterator to iterate the cityNames CityNames elements:
Iterator iterator = cityNames.iterator(); Delhi Mumbai Kolkata Chandigarh Noida
Java Vector
• Vector is like the dynamic array which can grow or • It is similar to the ArrayList, but with
shrink its size. Unlike array, we can store n- two differences-
number of elements in it as there is no size limit. It
is a part of Java Collection framework since Java
1.2. It is found in the java.util package and
implements the List interface, so we can use all the
• Vector is synchronized.
methods of List interface here. • Java Vector contains many legacy
methods that are not the part of a
collections framework.
• It is recommended to use the Vector class in the
thread-safe implementation only. If you don't need • Java Vector class Declaration
to use the thread-safe implementation, you should • public class Vector<E>
use the ArrayList, the ArrayList will perform better
in such case. • extends Object<E>
• The Iterators returned by the Vector class are fail- • implements List<E>, Cloneable,
fast. In case of concurrent modification, it fails and Serializable
throws the ConcurrentModificationException.
Java Vector Constructors
• Vector class supports four types of constructors. These are
given below:
Vector Methods
Java Vector Methods
Java Vector Example //Adding elements using addElement() method of
Vector
import java.util.*; vec.addElement("Rat");
public class VectorExample { vec.addElement("Cat");
vec.addElement("Deer");
public static void main(String
args[]) { System.out.println("Elements are: "+vec);
//Create a vector }
Vector<String> vec = new }
Vector<String>(); • Output:
//Adding elements using add() • Compile by: javac VectorExample.java
method of List
vec.add("Tiger"); • Run by: java VectorExample
vec.add("Lion");
vec.add("Dog"); • Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]
vec.add("Elephant");
Vector Example Output:
//Display the vector elements Values in vector: [100,
System.out.println("Values in vector: " +in); 200, 300, 200, 400, 500,
import java.util.*; //use remove() method to delete the first occurence of an element 600, 700]
public class VectorExample2 { System.out.println("Remove first occourence of element 200: Remove first occourence
"+in.remove((Integer)200)); of element 200: true
public static void main(String args[]) {
//Display the vector elements afre remove() method Values in vector: [100,
//Create an empty Vector
System.out.println("Values in vector: " +in); 300, 200, 400, 500, 600,
Vector<Integer> in = new Vector<>();
//Remove the element at index 4 700]
//Add elements in the vector System.out.println("Remove element at index 4: " +in.remove(4));
Remove element at index
in.add(100); System.out.println("New Value list in vector: " +in);
4: 500
New Value list in vector:
in.add(200); //Remove an element
[100, 300, 200, 400, 600,
in.add(300); in.removeElementAt(5);
700]
//Checking vector and displays the element
in.add(200); Vector element after
System.out.println("Vector element after removal: " +in);
in.add(400); removal: [100, 300, 200,
//Get the hashcode for this vector
in.add(500);
400, 600]
System.out.println("Hash code of this vector = "+in.hashCode()); Hash code of this vector =
in.add(600); //Get the element at specified index 130123751
in.add(700); System.out.println("Element at index 1 is = "+in.get(1)); Element at index 1 is =
} } 300
What is the difference between Iterator and
Enumeration?
Iterator Enumeration

1) The Iterator can traverse legacy and non- Enumeration can traverse only legacy elements.
legacy elements.

2) The Iterator is fail-fast. Enumeration is not fail-fast.

3) The Iterator is slower than Enumeration. Enumeration is faster than Iterator.

4) The Iterator can perform remove operation The Enumeration can perform only traverse operation
while traversing the collection. on the collection.
What is the difference between List and Set?
8) What is the difference between List and Set?
The List and Set both extend the collection interface. However, there are some differences between the both
which are listed below.
The List can contain duplicate elements whereas Set includes unique items.
The List is an ordered collection which maintains the insertion order whereas Set is an unordered collection
which does not preserve the insertion order.
The List interface contains a single legacy class which is Vector class whereas Set interface does not have any
legacy class.
The List interface can allow n number of null values whereas Set interface only allows a single null value.
Difference between List and Set
List(Interface) Set (Interface)
1.List is index based data structure . 1.It is not Indexed based data
structure.It store the data accordingly
2.List can store Duplicate element. to the hashcode values.
3.List can store any numbers of null 2.Set does not allow to store duplicate
values(because it allow duplicate element.
value). 3.Set can store only one null
4.List follows the insertion orders. values(because it don’t allow duplicate
value).
5.We can iterate(get) the List element 4.Set does not follows the insertion
b y I t e r a t o r ( F o r w a r d order.
direction)&ListIterator(Forward 5.We can iterate(get) the List element
&backward element can get). by Iterator(Forward direction)
Example of ArrayList(Interface)

import java.util.ArrayList; Output


import java.util.List;
public class Listdemo {
List of element
public static void main(String[] args){ [20, 30, 40]
List l=new ArrayList();
l.add(20);//add(index,value)by default it take 0
index value
l.add(1,30);
l.add(2,40);
I.add(3,60);
//l.add(5,60);//error
System.out.println("List of element");
System.out.println(l); }
Example of Arraylist and Hashset
package demo; HashSet h1=new HashSet();
import java.util.*; Set s1=new HashSet();//reference obj of Interface
Hashset
public class arraylist {
h1.add("Arjun");//Hashset obj contain different type of
public static void main(String args[]){ data
ArrayList a1=new ArrayList(); h1.add(30);
a1.add(20);//arraylist obj contain different type of data h1.add(true);
a1.add("parul"); System.out.println(h1);
a1.add('w'); }}
System.out.println(a1); output:
List l=new ArrayList();//reference obj of Interface List [20, parul, w]
[Arjun, 30, true]
How to remove duplicates from ArrayList in
Java?
public class RemoveDuplicateArrayList {
Output:
public static void main(String[] args) {
List<String> l = new ArrayList<String>();
l.add("Mango"); Before converting to set
l.add("Banana");
l.add("Mango");
[Mango, Banana, Mango, Apple]
l.add("Apple"); After converting to set
System.out.println(l.toString());
[Mango, Banana, Apple]
Set<String> s = new LinkedHashSet<String>(l);
System.out.println(s);
}
}
Set Interface

• The set interface is inherited from the Java try { Output :[65, 21, 53,
collections Interface A Set interface for (int i = 0; i <= 5; i++) { 22, 23, 43]
cannot store duplicate/redundant elements set.add(count[i]);} The sorted list is:
in it.It store unique values Here’s an [21, 22, 23, 43, 53,
System.out.println(set);
65]
example based on a set interface. TreeSet<Integer> sortedSet = First element of the
package VIPS; new TreeSet<Integer>(set); set is: 21
last element of the
import java.util.*; System.out.println("The sorted list is:");
set is: 65
System.out.println(sortedSet);
public class SetExample {
System.out.println("First element of the set is: " + (Integer)
public static void main(String args[]) { sortedSet.first());

int count[] = { 21, 23, 43, 53, 22, 65 }; System.out.println("last element of the set is: " + (Integer)
sortedSet.last());
Set<Integer> set = new HashSet<Integer>(); } catch (Exception e) {}}}
HashSet:
• Java HashSet class creates a
collection that use a hash table
for storage. Hashset only contain
unique elements and it inherits
the Abstract Set class and
implements Set interface
Map Interface
• A Map is an object that maps keys to import java.util.HashMap;
values. A map cannot contain public class hashmap {
duplicate keys: Each key can map to public static void main(String[] args){
at most one value. It models the HashMap hm=new HashMap();//HasMap store
mathematical function abstraction. value in Key-value pair
hm.put(67, "Shruti");
• The Java platform contains three
hm.put(68, "Komal");
general-purpose Map
hm.put(69, "Yashdeep");
implementations: HashMap,
TreeMap, and LinkedHashMap. System.out.println(hm);
Their behavior and performance are }}
precisely analogous to HashSet, OUTPUT:{67=Shruti, 68=Komal, 69=Yashdeep}
TreeSet, and LinkedHashSet, as
How to reverse ArrayList?
{
import java.util.ArrayList; System.out.println(i.next());
import java.util.Collection; }
import java.util.Collections; Iterator i2 = list.iterator();

import java.util.Iterator; Collections.reverse(list);

import java.util.List; System.out.println("printing list in reverse order....");

public class ReverseArrayList { while(i2.hasNext())

public static void main(String[] args) { {


System.out.println(i2.next());
List list = new ArrayList<>();
} } }
list.add(10);
Outputprinting the list....
list.add(50);
10
list.add(30);
50
Iterator i = list.iterator();
30
System.out.println("printing the list....");
printing list in reverse order....
while(i.hasNext())
30 50 10
Hashset and Treeset example TreeSet Class is a NavigableSet implementation based on TreeMap. Here, the elements are
package VIPS; ordered using comparators.

import java.util.HashSet; Let us check an example based on TreeSet Class.

public class HashSetClass { //TreeSet

public static void main(String args[]) { package VIPS;

HashSet<String> hset = new HashSet<String>(); import java.util.TreeSet;

hset.add("Suzuki"); public class TreeSetClass {

hset.add("Kawasaki"); public static void main(String args[]) {

hset.add("Honda"); TreeSet<Integer> treeset = new TreeSet<Integer>();

hset.add("Ducati"); treeset.add(8476);

hset.add("Yamaha"); treeset.add(748);

hset.add("Yamaha"); treeset.add(88);

hset.add("Suzuki"); treeset.add(983);

hset.add(null); treeset.add(18);

hset.add(null); treeset.add(0);

// Displaying HashSet elements System.out.println(treeset); }

System.out.println(hset);}} }

OUTPUT: OUTPUT:

[null, Suzuki, Ducati, Yamaha, Kawasaki, Honda] [0, 18, 88, 748, 983, 8476]
How to synchronize List, Set and Map elements?
• Yes, Collections class provides methods to Q What is the advantage of the generic
make List, Set or Map elements as collection?
synchronized: • There are three main advantages of
using the generic collection.
• public static List synchronizedList(List l){}
• public static Set synchronizedSet(Set s){} • If we use the generic class, we don't
need typecasting.
• public static SortedSet
synchronizedSortedSet(SortedSet s){} • It is type-safe and checked at
compile time.
• public static Map synchronizedMap(Map
m){} • Generic confirms the stability of the
code by making it bug detectable at
• public static SortedMap compile time.
synchronizedSortedMap(SortedMap m){}
Q What is hash-collision in Hashtable and • QWhat is the default size of load factor in
how it is handled in Java? hashing based collection?
• Two different keys with the same hash value • The default size of load factor is 0.75. The
are known as hash-collision. Two separate default capacity is computed as initial capacity
entries will be kept in a single hash bucket * load factor. For example, 16 * 0.75 = 12. So,
to avoid the collision. There are two ways to 12 is the default capacity of Map.
avoid hash-collision.
• Separate Chaining • Q What do you understand by fail-fast?
• Open Addressing • The Iterator in java which immediately throws
ConcurrentmodificationException, if any
Q What is the Dictionary class?
structural modification occurs in, is called as a
• The Dictionary class provides the capability Fail-fast iterator. Fail-fats iterator does not
to store key-value pairs. require any extra space in memory.
What is the difference between HashSet and
TreeSet and HashMap?
What is the difference between HashSet and HashMap?
• The HashSet and TreeSet, both classes,
• The differences between the HashSet and HashMap are
implement Set interface. The differences listed below.
between the both are listed below. • HashSet contains only values whereas HashMap includes
the entry (key, value). HashSet can be iterated, but
HashMap needs to convert into Set to be iterated.
• HashSet maintains no order whereas • HashSet implements Set interface whereas HashMap
TreeSet maintains ascending order. implements the Map interface
• HashSet cannot have any duplicate value whereas
• HashSet impended by hash table whereas HashMap can contain duplicate values with unique keys.
TreeSet implemented by a Tree structure. • HashSet contains the only single number of null value
• HashSet performs faster than TreeSet. whereas HashMap can hold a single null key with n
number of null values.
• HashSet is backed by HashMap whereas
TreeSet is backed by TreeMap.
What is the difference between Comparable and
Comparator and Collection and Collections ?
The differences between the Collection and Comparable Comparator
Collections are given below.

Comparable provides The Comparator provides


v The Collection is an interface whereas Collections is a only one sort of sequence. multiple sorts of
class. sequences.
v The Collection interface provides the standard
functionality of data structure to List, Set, and Queue. It provides one method It provides one method
However, Collections class is to sort and synchronize
the collection elements.
named compareTo(). named compare().

v The Collection interface provides the methods that


can be used for data structure whereas Collections It is found in java.lang It is located in java.util
class provides the static methods which can be used package package.
for various operation on a collection.
If we implement the The actual class is not
Comparable interface, changed.
The actual class is 1
modified.
List Interface
• The List interface is derived
//List Interface
package VIPS;

from the java util package. The import java.util.*;

List enables the user to maintain public class ListInterface {

an ordered collection of elements


public static void main(String args[]) {
List<String> list = new ArrayList<String>();

with the help of indexing list.add("David");

methods and can perform data list.add("Jhon");


list.add("Stacy");
manipulation operations such as //list.add("Stacy");

insert, update, delete, and many for (String Students : list)

more.
System.out.println(Students);
}
}
Java collections: Queue

vQueue 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.Queue is in java is a collection that is capable
to store and apply operations on elements
vPriority 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.
Example Queue
package VIPS; queue.add("Lily");
import java.util.*; System.out.println(queue);
queue.remove("Lily");
public class QueueInterface {
public static void main(String args[]) { System.out.println("Queue total size: "
Queue<String> queue = new +queue.size());
LinkedList<String>(); System.out.println("Queue includes
flowers 'Lily': ?" +
queue.add("Rose"); queue.contains("Lily"));
queue.add("Lotus"); queue.clear();}
queue.add("Habiscus"); } Output
[Rose, Lotus, Habiscus, Lily]
Queue total size: 3
Queue includes flowers 'Lily': ?false
What do you understand by BlockingQueue?
• BlockingQueue is an interface which extends the Queue interface. It
provides concurrency in the operations like retrieval, insertion,
deletion. While retrieval of any element, it waits for the queue to be
non-empty. While storing the elements, it waits for the available space.
BlockingQueue cannot contain null elements, and implementation of
BlockingQueue is thread-safe.
• Syntax
• public interface BlockingQueue<E> extends Queue <E>
What does the hashCode() method?
• The hashCode() method returns a hash code value (an integer number).

• The hashCode() method returns the same integer number if two keys (by calling equals()
method) are identical.

• However, it is possible that two hash code numbers can have different or the same keys.

• If two objects do not produce an equal result by using the equals() method, then the
hashcode() method will provide the different integer result for both the objects.
Why we override equals() method?

• The equals method is used to check whether two objects are the same
or not. It needs to be overridden if we want to check the objects based
on the property.

• For example, Employee is a class that has 3 data members: id, name,
and salary. However, we want to check the equality of employee
object by the salary. Then, we need to override the equals() method.
How to convert ArrayList to Array and Array to
ArrayList?
• We can convert an Array to ArrayList by using the asList() method of
Arrays class. asList() method is the static method of Arrays class and
accepts the List object. Consider the following syntax:

• Arrays.asList(item)
• We can convert an ArrayList to Array using toArray() method of the
ArrayList class. Consider the following syntax to convert the
ArrayList to the List object.

• List_object.toArray(new String[List_object.size()])
How to make Java ArrayList Read-Only?

• We can obtain java ArrayList Read-only by calling the


Collections.unmodifiableCollection() method. When we define an
ArrayList as Read-only then we cannot perform any modification in
the collection through add(), remove() or set() method.
Collection package Question
Q When to use ArrayList and LinkedList?
• LinkedLists are better to use for the update operations whereas
ArrayLists are better to use for the search operations.
Q How to synchronize ArrayList?
• We can synchronize ArrayList in two ways.
• Using Collections.synchronizedList() method
• Using CopyOnWriteArrayList<T>
PriorityQueue
PriorityQueue
import java.util.*; }
class QueueExample { Output:
queue.remove(); head:Amit
public static void main(String args[]){
queue.poll(); head:Amit
PriorityQueue<String> queue=new PriorityQueue<String>();
iterating the
// creating priority queue System.out.println("after removing two queue elements:
queue.add("Amit"); elements:"); Amit
// adding elements Iterator<String> itr2=queue.iterator(); Rachit
queue.add("Rachit"); Rahul
while(itr2.hasNext()){
queue.add("Rahul"); after removing
System.out.println("head:"+queue.element());
System.out.println(itr2.next()); two elements:
Rahul
System.out.println("head:"+queue.peek()); }
System.out.println("iterating the queue elements:"); }
Iterator itr=queue.iterator();
}
while(itr.hasNext()){
System.out.println(itr.next());
Queue Interface

• A Queue interface is inherited Example://Queue Interface


package VIPS;
from the Java Collections import java.util.*;
interface. The Queue is a linear public class QueueInterface {public static void main(String[] args) {
C o l l e c t i o n t h a t o ff e r s d a t a Queue<String> queue = new LinkedList<>();

manipulation operations on the queue.add("Apple");queue.add("Mango");

collection elements, and follows queue.add("Grapes");


queue.add("Banana");
the FIFO(First In First Out) System.out.println(queue);
principle. For example: queue.remove("Grapes");
System.out.println(queue);
System.out.println("Queue total Size: " + queue.size());
System.out.println("Queue includes fruit 'Apple'? : " +
queue.contains("Apple"));
queue.clear();
}}
Deque interface
Example://Deque Interface
package VIPS;
• A Deque interface is inherited import java.util.ArrayDeque;

from the Java Collections import java.util.Deque;

Interface. The term Deque stands public class DequeInterface {public static void main(String[] args) {
Deque<Integer> num = new ArrayDeque<>();
for Double-Ended Queue. The num.offer(10);num.offerLast(21);num.offerFirst(52);
Deque supports insertion and System.out.println("Deque elements: " + num);
deletion operations on both sides int first = num.peekFirst();

of the Queue. System.out.println("First Element is: " + first);


int lastElement = num.peekLast();System.out.println("Last Element: "
+ lastElement);
int removed = num.pollFirst();System.out.println("Removed First
Element: " + removed);System.out.println("Updated Deque is: " +
num);
}}

You might also like