0% found this document useful (0 votes)
54 views63 pages

VIPS OOPS Unit 2 Collection API Interface

Uploaded by

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

VIPS OOPS Unit 2 Collection API Interface

Uploaded by

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

Faculty : Dr.

Nishtha Kansal
Assistant Professor
VIPS
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.
• 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 LinkedList is better to manipulate data.
data.
ArrayList provides random access. LinkedList does not provide random
access.
ArrayList takes less memory overhead as LinkedList takes more memory
it stores only object overhead, 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
compulsory for them to make an instance of the to its numerous advantages. The advantages
Iterator interface from the collection of objects
they desire to traverse over. After that, the received of Java Iterator are given as follows -
Iterator maintains the trail of the components in • The user can apply these iterators to any of
the underlying collection to make sure that the user the classes of the Collection framework.
will traverse over 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
traversing over an Iterator leading to that cannot modernize(add/remove) the
collection, then the Iterator will typically Collection, whereas, if they use the Java
acknowledge it and will throw an exception in the Iterator, they can simply update the
next time when the user will attempt to get the next Collection.
component from the Iterator.
Disadvantages of Java Iterator
Despite the numerous advantages, the Java Iterator has
various disadvantages also. The disadvantages of the Java
• Java Iterator Methods
Iterator are given below -
• The following figure perfectly
• The Java Iterator only preserves the iteration in the displays the class diagram of the
forward direction. In simple words, the Java Iterator is a
uni-directional Iterator.
Java Iterator interface. It contains
• The replacement and extension of a new component are a total of four methods that are:
not approved by the Java Iterator.
• In CRUD Operations, the Java Iterator does not hold the
various operations like CREATE and UPDATE.
• In comparison with the Spliterator, Java Iterator does not • hasNext()
support traversing elements in the parallel pattern which
implies that Java Iterator supports only Sequential • next()
iteration.
• In comparison with the Spliterator, Java Iterator does not • remove()
support 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
was added in the Java 8. Let's parameter. It returns E, i.e., the next
discuss each method in detail. element in the traversal. If the iteration or
collection of objects has no more elements
left to iterate, then it throws the
• boolean hasNext(): The method NoSuchElementException.
does not accept any parameter. It • default void remove(): This method also
does not require any parameters. There is
returns true if there are more no return type of this method. The main
elements left in the iteration. If function of this method is to remove the
there are no more elements left, last element returned by the iterator
then it will return false. traversing through the underlying
collection.
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() + " ");
{
ArrayList<String> cityNames = new ArrayList<String>();
System.out.println();
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
shrink its size. Unlike array, we can store n- • It is similar to the ArrayList, but with
number of elements in it as there is no size limit. It two differences-
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
• It is recommended to use the Vector class in the
thread-safe implementation only. If you don't need
collections framework.
to use the thread-safe implementation, you should • Java Vector class Declaration
use the ArrayList, the ArrayList will perform better
in such case. • public class Vector<E>
• The Iterators returned by the Vector class are fail- • extends Object<E>
fast. In case of concurrent modification, it fails and
throws the ConcurrentModificationException. • implements List<E>, Cloneable,
Serializable
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");
public static void vec.addElement("Deer");
main(String args[]) {
//Create a vector
System.out.println("Elements
Vector<String> vec = are: "+vec);
new Vector<String>(); }
//Adding elements using }
add() method of List • Output:
vec.add("Tiger"); • Compile by: javac VectorExample.java
vec.add("Lion");
• Run by: java VectorExample
vec.add("Dog");
vec.add("Elephant"); • Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]
Vector Example Output:
//Display the vector elements Values in vector: [100,
System.out.println("Values in vector: " +in);
200, 300, 200, 400, 500,
//use remove() method to delete the first occurence of an element
import java.util.*; System.out.println("Remove first occourence of element 200: 600, 700]
public class VectorExample2 { "+in.remove((Integer)200)); Remove first occourence
public static void main(String args[]) {
//Display the vector elements afre remove() method of element 200: true
System.out.println("Values in vector: " +in); Values in vector: [100,
//Create an empty Vector //Remove the element at index 4
System.out.println("Remove element at index 4: "
300, 200, 400, 500, 600,
Vector<Integer> in = new Vector<>(); +in.remove(4)); 700]
//Add elements in the vector System.out.println("New Value list in vector: " +in); Remove element at index
//Remove an element 4: 500
in.add(100); in.removeElementAt(5);
//Checking vector and displays the element
New Value list in vector:
in.add(200);
System.out.println("Vector element after removal: " +in); [100, 300, 200, 400, 600,
in.add(300); //Get the hashcode for this vector 700]
in.add(200); System.out.println("Hash code of this vector = "+in.hashCode()); Vector element after
//Get the element at specified index
in.add(400); System.out.println("Element at index 1 is = "+in.get(1));
removal: [100, 300, 200,
in.add(500); } } 400, 600]
Hash code of this vector
in.add(600);
= 130123751
in.add(700); Element at index 1 is =
300
Enumerated data type
• The Enum in Java is a data type which • Java Enum internally inherits the
contains a fixed set of constants.
Enum class, so it cannot inherit
• It can be used for days of the week
any other class, but it can
(SUNDAY, MONDAY, TUESDAY, implement many interfaces. We
WEDNESDAY, THURSDAY, FRIDAY, and can have fields, constructors,
SATURDAY) , directions (NORTH, methods, and main methods in
SOUTH, EAST, and WEST), season
(SPRING, SUMMER, WINTER, and Java enum.
AUTUMN or FALL), colors (RED,
YELLOW, BLUE, GREEN, WHITE, and
BLACK) etc. According to the Java naming
conventions, we should have all constants in
capital letters. So, we have enum constants
in capital letters.
Points to remember for Java Enum
Enum improves type safety class EnumExample1{
Enum can be easily used in //defining the enum inside the class
switch public enum Season { WINTER,
SPRING, SUMMER, FALL }
Enum can be traversed
//main method
Enum can have fields,
public static void main(String[] args) {
constructors and methods
//traversing the enum
Enum may implement many
for (Season s : Season.values())
interfaces but cannot extend any
class because it internally System.out.println(s);
Output:WINTER
SPRING
extends Enum class }} SUMMER
FALL
Enum – Enumeration in Java Example
• An enumeration (enum for short) Here's an example:
enum Colors {
in Java is a special data type RED,
which contains a set of BLUE,
predefined constants. YELLOW,
GREEN
• How to Create an Enum in Java }
• To create an enum, we use the In the code above, we created an enum called
Colors. You may notice that the values of this
enum keyword, similar to how enum are all written in uppercase – this is just a
you'd create a class using the general convention. You will not get an error if
the values are lowercase.
class keyword. Each value in an enum is separated by a
comma.Next, we're going to create a new variable
and assign one of the values of our enum to it.
Enum example:
enum Colors { • This is similar to initializing any
RED,
BLUE,
other variable. In the code above,
YELLOW, we initialized a Colors variable
GREEN and assigned one of the values of
}public class Main { an enum to it using the dot
public static void main(String[] args) {
syntax: Colors red =
Colors red = Colors.RED;
Colors.RED;.

System.out.println(red);
// RED
}
}
Enum ordinal()function
enum Colors { • // 0
RED, • }
BLUE,
•}
YELLOW,
GREEN
Output :red.ordinal() from the
code above returns 0.
}
public class Main {
public static void main(String[] args) {
Colors red = Colors.RED;
System.out.println(red.ordinal());
How to Use an Enum in a Switch
Statement
• In this section, we'll se how we can use an enum in a case BLUE:
switch statement.
System.out.println("The color is blue");
• Here is an example:
break;
public class Main {
case YELLOW:
enum Colors {
RED, System.out.println("The color is yellow");
BLUE, break;
YELLOW, case GREEN:
GREEN System.out.println("The color is green");
} break;
public static void main(String[] args) { }
Colors myColor = Colors.YELLOW; }
switch(myColor) { }
case RED: This is a very basic example of how we can use an enum
System.out.println("The color is red"); in a switch statement. We would get "The color is
yellow" printed to the console because that is the only
break; case that matches the switch statement's condition.
How to Loop Through the Values of an Enum
enum in Java has a values() method that returns an array of the values
of an enum. We're going to use a for-each loop to iterate through and /*
print the values of our enum.
RED
Here's how we can do that: BLUE
enum Colors {
YELLOW
RED,
BLUE, GREEN
YELLOW,
*/
GREEN
public class Main { }
public static void main(String[] args) {
for (Colors allColors : Colors.values()) {
System.out.println(allColors);
}
}
Conclusion
• In this ,we got to know what an
enum is in Java,
I
how to create it,
and how to assign its values to
other variables.

• We also saw how to use use the


enum type with a switch
statement and how we can loop
through the values of an enum.
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 to the hashcode
2.List can store Duplicate element. 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
by Iterator(Forward 4.Set does not follows the insertion order.
direction)&ListIterator(Forward 5.We can iterate(get) the List element by
&backward element can get). 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
public class arraylist { Interface Hashset
public static void main(String args[]){ h1.add("Arjun");//Hashset obj contain
different type of 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 [20, parul, w]
Interface List [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());
Set<String> s = new
[Mango, Banana, Apple]
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 The sorted list is:
set.add(count[i]);} [21, 22, 23, 43, 53,
in it.It store unique values Here’s an 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
import java.util.*; last element of the
System.out.println("The sortedset listis:is:");
65
public class SetExample { System.out.println(sortedSet);
public static void main(String args[]) { System.out.println("First element of the set
is: " + (Integer) sortedSet.first());
int count[] = { 21, 23, 43, 53, 22, 65 };
System.out.println("last element of the set
Set<Integer> set = new HashSet<Integer>(); is: " + (Integer) sortedSet.last());
} 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
mathematical function abstraction. store value in Key-value pair
• The Java platform contains three hm.put(67, "Shruti");
general-purpose Map hm.put(68, "Komal");
implementations: HashMap, hm.put(69, "Yashdeep");
TreeMap, and LinkedHashMap. System.out.println(hm);
Their behavior and performance are }}
precisely analogous to HashSet, OUTPUT:{67=Shruti, 68=Komal,
TreeSet, and LinkedHashSet, as 69=Yashdeep}
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();
Collections.reverse(list);
import java.util.Iterator;
System.out.println("printing list in reverse order....");
import java.util.List;
public class ReverseArrayList { while(i2.hasNext())
public static void main(String[] args) { {
List list = new ArrayList<>(); System.out.println(i2.next());
} } }
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
• public static SortedSet need typecasting.
synchronizedSortedSet(SortedSet s){}
• public static Map synchronizedMap(Map
• It is type-safe and checked at compile
m){} time.
• public static SortedMap • Generic confirms the stability of the
synchronizedSortedMap(SortedMap m){} code by making it bug detectable at
compile time.
Q What is hash-collision in Hashtable • QWhat is the default size of load factor in
and how it is handled in Java? hashing based collection?
• Two different keys with the same hash • The default size of load factor is 0.75. The
value are known as hash-collision. Two default capacity is computed as initial
separate entries will be kept in a single capacity * load factor. For example, 16 *
0.75 = 12. So, 12 is the default capacity of
hash bucket to avoid the collision. There Map.
are two ways to avoid hash-collision.
• Separate Chaining
• Q What do you understand by fail-fast?
• Open Addressing • The Iterator in java which immediately
Q What is the Dictionary class? throws ConcurrentmodificationException, if
• The Dictionary class provides the any structural modification occurs in, is
called as a Fail-fast iterator. Fail-fats iterator
capability to store key-value pairs. does not require any extra space in memory.
What is the difference between HashSet and TreeSet and HashMap?

What is the difference between HashSet and


• The HashSet and TreeSet, both classes, HashMap?
implement Set interface. The differences • The differences between the HashSet and
between the both are listed below. HashMap are listed below.
• HashSet contains only values whereas HashMap
includes the entry (key, value). HashSet can be
• HashSet maintains no order whereas iterated, but HashMap needs to convert into Set to
TreeSet maintains ascending order. be iterated.
• HashSet impended by hash table whereas • HashSet implements Set interface whereas
HashMap implements the Map interface
TreeSet implemented by a Tree structure.
• HashSet cannot have any duplicate value whereas
• HashSet performs faster than TreeSet. HashMap can contain duplicate values with unique
keys.
• HashSet is backed by HashMap whereas
• HashSet contains the only single number of null
TreeSet is backed by TreeMap. value whereas HashMap can hold a single null key
with n number of null values.
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
only one sort of multiple sorts of
 The Collection is an interface whereas sequence. sequences.
Collections is a class.
 The Collection interface provides the standard It provides one method It provides one method
named compareTo(). named compare().
functionality of data structure to List, Set, and
Queue. However, Collections class is to sort
It is found in java.lang It is located in java.util
and synchronize the collection elements. package package.
 The Collection interface provides the methods
that can be used for data structure whereas If we implement the The actual class is not
Collections class provides the static methods Comparable interface, changed.
which can be used for various operation on a The actual class is 1
collection. 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[]) {
with the help of indexing List<String> list = new ArrayList<String>();
list.add("David");
methods and can perform data
list.add("Jhon");
manipulation operations such as list.add("Stacy");
insert, update, delete, and many //list.add("Stacy");
more. for (String Students : list)
System.out.println(Students);
}
}
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.Queue is in java is a collection that is capable to
store and apply operations on elements
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.
Example Queue
package VIPS; queue.add("Lily");
import java.util.*; System.out.println(queue);
public class QueueInterface { queue.remove("Lily");
public static void main(String args[])
{ System.out.println("Queue total size: "
+queue.size());
Queue<String> queue = new
LinkedList<String>(); System.out.println("Queue includes
flowers 'Lily': ?" +
queue.add("Rose"); queue.contains("Lily"));
queue.add("Lotus"); Output
queue.clear();}
[Rose, Lotus, Habiscus, Lily]
queue.add("Habiscus"); } 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:
public static void main(String args[]){
queue.remove(); head:Amit
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 Rachit
queue.add("Rachit");
Iterator<String> itr2=queue.iterator(); Rahul
queue.add("Rahul"); while(itr2.hasNext()){ after removing
two elements:
System.out.println("head:"+queue.element()); System.out.println(itr2.next()); 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) {
Collection that offers data Queue<String> queue = new LinkedList<>();
manipulation operations on the queue.add("Apple");queue.add("Mango");
queue.add("Grapes");
collection elements, and follows queue.add("Banana");
the FIFO(First In First Out) System.out.println(queue);
queue.remove("Grapes");
principle. For example: 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;
import java.util.ArrayDeque;
• A Deque interface is inherited import java.util.Deque;
from the Java Collections public class DequeInterface {public static void main(String[]
args) {
Interface. The term Deque stands Deque<Integer> num = new ArrayDeque<>();
for Double-Ended Queue. The num.offer(10);num.offerLast(21);num.offerFirst(52);
System.out.println("Deque elements: " + num);
Deque supports insertion and int first = num.peekFirst();
deletion operations on both sides System.out.println("First Element is: " + first);
int lastElement = num.peekLast();System.out.println("Last
of the Queue. Element: " + lastElement);
int removed = num.pollFirst();System.out.println("Removed
First Element: " + removed);System.out.println("Updated
Deque is: " + num);
}}

You might also like