CollectionFramework
CollectionFramework
—------------------
Collection is an object, it is able to manage a group of other objects
as a single unit.
2. Arrays are able to allow only Homogeneous elements, arrays are not
allowing heterogeneous elements. If we add heterogeneous elements to
the arrays then we are able to get the compilation error like
Incompatible Types.
EX:
Student[] stds = new Student[3];
stds[0] = new Student();
stds[1] = new Employee(); —-> Incompatible Types Error
Set is not index based, where all the elements are not arranged as per
the indexes, but all the elements are arranged as per the element’s
Hashcode values.
Collection:
—--------
1. It represents a group of other objects as a single entity / It is
able to represent a group of individual elements as a single
unit.
2. It is a root interface for all the collection objects.
3. It was provided by JAVA in its JDK1.2 version.
4. It has defined a number of methods in order to implement these
methods by all the Collection implementation classes.
Methods:
—-----
1. public boolean add(Object obj)
—-------------------------
It can be used to add the specified element to the Collection
object. If the element is added to the Collection object
successfully then add() method will return true value, if the
element is not added to the Collection object then add() method
will return false value.
EX:
import java.util.HashSet;
import java.util.Set;
}
}
true
true
true
true
[AAA, CCC, BBB, DDD]
false
false
false
false
[AAA, CCC, BBB, DDD]
2. public boolean addAll(Collection c):
—----------------------------
It is able to add all the elements of the Specified Collection to
the present Collection object, if at least one element is added
then it will return true value, if no element is added then it
will return false value.
EX:
import java.util.Collection;
import java.util.HashSet;
}
}
}
}
}
}
}
}
EX:
import java.util.ArrayList;
import java.util.Collection;
}
}
EX:
import java.util.ArrayList;
import java.util.Collection;
public class Main {
public static void main(String[] args) {
Collection collection1 = new ArrayList();
collection1.add("AAA");
collection1.add("BBB");
collection1.add("CCC");
collection1.add("DDD");
collection1.add("EEE");
collection1.add("FFF");
System.out.println(collection1);
Collection collection2 = new ArrayList();
collection2.add("BBB");
collection2.add("CCC");
collection2.add("DDD");
collection2.add("XXX");
collection2.add("YYY");
System.out.println(collection2);
System.out.println(collection1.retainAll(collecti
on2));
System.out.println(collection1);
}
}
EX:
import java.util.ArrayList;
import java.util.Collection;
EX:
import java.util.ArrayList;
import java.util.Collection;
public class Main {
public static void main(String[] args) {
Collection collection1 = new ArrayList();
collection1.add("AAA");
collection1.add("BBB");
collection1.add("CCC");
collection1.add("DDD");
collection1.add("EEE");
collection1.add("FFF");
System.out.println(collection1);
System.out.println(collection1.size());
System.out.println(collection1.isEmpty());
collection1.clear();
System.out.println(collection1.isEmpty());
}
}
EX:
import java.util.ArrayList;
import java.util.Collection;
List:
—-----
1. It is a child interface to Collection interface.
2. It was introduced in JDK1.2 version.
3. It is able to represent a group of elements as a single
entity.
4. It is index based.
5. It allows Duplicate elements.
6. It follows insertion order.
7. It does not follow Sorting Order.
8. It allows any number of null elements.
9. It allows Heterogeneous elements.
Methods:
1. public void add(int index, Object obj)
It can be used to add the specified element at the
specified index in the List object.
EX:
import java.util.ArrayList;
import java.util.List;
EX:
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
}
}
}
}
EX:
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
}
}
Q)What are the differences between add() method and set() method?
—----------------------------------------------------------------
Ans:
—----
1. add() method is mainly for inserting a new element in the list at
the specified index value, if any element exists at the specified
index then that existing element will be adjusted to the next
index and the new element will be added to the specified index,
if we provide the index value which is after the last index then
add() method will add the specified element as last element
without raising any exception.
EX:
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
}
}
[AAA, BBB, CCC, DDD, EEE]
[AAA, BBB, XXX, CCC, DDD, EEE]
[AAA, BBB, XXX, CCC, DDD, EEE, YYY]
}
}
Note: in the above two methods, if the specified element does not
exist then indexOf() and lastindexOf() methods will return -1
value.
EX:
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
EX:
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
ArrayList:
—---------
1. It was introduced in JDK1.2 version.
2. It is not a Legacy Collection.
3. It is a direct implementation class to List interface.
4. It is index based.
5. It allows duplicate elements.
6. It follows insertion order.
7. It does not follow Sorting Order.
8. It allows heterogeneous elements.
9. It allows any number of null elements.
Resizable Array:
When we create an ArrayList in Java applications , its initial
capacity is 10 elements, that is, ArrayList will create an array
of 10 size, if we add elements to the ArrayList, automatically
all these elements will come to the internal Array, if we add
11th [Exceeding max capacity] element to the ArrayList then
ArrayList will create another new array with the capacity 16
[CurrentCapacity*3/2+1], ArrayList will copy all the elements
from the existing array to new array and ArrayList will refer new
Array, where the existed array is eligible for Garbage
Collection.
Constructors:
—-------------
1. public ArrayList():
It can be used to create an empty ArrayList object with the
initial capacity 10 .
import java.util.ArrayList;
[]
[]
EX:
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.PriorityQueue;
}
}
EX:
import java.util.ArrayList;
Vector:
—------
1. It was provided by Java in its JDK1.0 version.
2. It is a Legacy Collection.
3. It is a direct implementation class to List interface.
4. It is index based.
5. It allows Duplicate elements.
6. It follows Insertion order.
7. It does not follow Sorting order.
8. It allows Heterogeneous elements.
9. It allows any number of null elements.
Constructors:
1. public Vector():
It can be used to create an empty Vector object with the initial
capacity value 10.
EX:
import java.util.ArrayList;
import java.util.Vector;
EX:
import java.util.ArrayList;
import java.util.Vector;
[]
20
3. public Vector(int capacity, int incrementalRatio)
It can be used to create an empty Vector object with the
specified initial capacity value and with the specified
incrementalCapacity value.
EX:
import java.util.ArrayList;
import java.util.Vector;
[]
5
EX:
import java.util.ArrayList;
import java.util.Vector;
10
20
40
EX:
import java.util.ArrayList;
import java.util.Vector;
5
10
15
4. public Vector(Collection c)
It can be used to create a Vector object with all the elements of
the Specified Collection object.
Note: It can be used to convert the elements from all the types
of Collections like List, Set and Queue to the Vector.
EX:
import java.util.*;
public class Main {
public static void main(String[] args) {
List list = new ArrayList();
list.add("AAA");
list.add("BBB");
list.add("CCC");
Vector vector1 = new Vector(list);
System.out.println(vector1);
Methods:
—---------
1. public void addElement(Object obj)
It can be used to add the specified element to the vector
object.
EX:
import java.util.*;
}
}
EX:
import java.util.*;
}
}
}
}
}
}
EX:
import java.util.*;
}
}
Stack:
—-----
Stack is a Collection, it is a subclass to the Vector, It is able to
arrange all the elements as per positions starts from 1 to size , it
follows LIFO[Last In First Out] to retrieve all the elements.
Constructor:
public Stack():
It is able to create an empty Stack.
import java.util.*;
[]
Methods:
1. public void push(Object element):
It inserted the specified element at the TOP of the stack.
2. public Object pop():
It is able to read and remove the top of the stack.
EX:
import java.util.*;
}
}
LinkedList:
—-----------
1. It was introduced in JDK1.2 version.
2. It is not a Legacy Collection.
3. It is a direct implementation class to List.
4. It is index based.
5. It allows duplicate elements
6. It follows insertion order.
7. It does not follow Sorting Order.
8. It allows Heterogeneous elements.
9. It allows any number of null values.
Constructors:
1. Public LinkedList():
It can be used to create an empty LinkedList object.
EX:
import java.util.*;
}
}
[]
2. public LinkedList(Collection c) :
It can be used to create a LinkedList object with all the
elements of the specified Collection.
}
}
Methods:
1. public void addFirst(Object element):
It can be used to add the specified element as the first
element.
EX:
import java.util.*;
EX:
import java.util.*;
OP: [AAA,BBB,CCC,DDD]
If we pass any Collection object reference variable as a parameter to
System.out.println() method then JVM will access toString() method
over the provided reference variable.
In Java , all the Collection classes have overridden the Object class
provided toString() method in such a way that to return a String
contains all the elements of the respective collection by enclosing
with [].
import java.sql.Array;
import java.util.*;
public class Main {
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add("AAA");
al.add("BBB");
al.add("CCC");
al.add("DDD");
System.out.println(al);
}
}
1. Enumeration
2. Iterator
3. ListIterator
Enumeration:
—------------
1. It was introduced in the JDK1.0 version.
2. It is a Legacy Cursor, it will be used for only Legacy
Collections.
3. It is able to perform only read operations while iterating
elements, it is not able to perform the operations like remove,
insert and replace,...
4. It is represented in the form of an interface like
java.util.Enumeration
To use Enumeration in Java applications we have to use the following
steps.
b. If the next element exists then read the next element and move
the cursor to the next position.
public Object nextElement()
Note: By repeating the above two steps we are able to read all
the elements from Enumeration.
import java.sql.Array;
import java.util.*;
}
}
Iterator:
—----------
1. Iterator was provided in JDK1.2 version.
2. It is not a legacy Cursor.
3. It is applicable for all the types of Collections, so it is also
called “Universal Cursor”.
4. It allows both read and remove operations while iterating
elements.
5. It is represented by JAVA in the form of an interface
“java.util.Iterator”.
6. To create an Iterator object we have to use the following method
from all the Collection classes.
}
}
Drawbacks:
1. It allows us to perform only read and remove operations, it does
not allow insert and replace operations.
2. It allows us to read elements in only Forward Direction, not in
backward direction.
ListIterator:
—------------
1. It was introduced in JDK1.2 version.
2. It is not a Legacy Cursor.
3. It is applicable for only List implementations.
4. It allows the user to perform the operations like read, remove,
insert and replace while iterating elements.
5. It allows you to read all the elements in both Forward direction
and Backward direction.
6. It is represented in the form of an interface
java.util.ListIterator.
To create a ListIterator object we have to use the following method
from the List implementation classes.
public ListIterator listIterator()
To read elements in Forward direction we have to use the following
methods.
public boolean hasNext()
public Object next()
public int nextIndex()
EX:
import java.util.LinkedList;
import java.util.ListIterator;
}
}
EX:
import java.util.LinkedList;
import java.util.ListIterator;
}
System.out.println(linkedList);
}
}
[AAA, BBB, CCC, DDD, EEE, FFF]
[AAA, CCC, DDD, XXX, YYY, FFF]
HashSet:
—--------
1. It was provided by JAVA in its JDK1.2 version.
2. It is not a Legacy Collection.
3. It is a direct implementation class to Set interface.
Constructors:
1. public HashSet():
It is able to create an empty hashSet object with the initial
capacity 16 elements and with the default fill ratio is 75%.
EX:
import java.util.HashSet;
[]
EX:
import java.util.HashSet;
[]
EX:
import java.util.HashSet;
[]
EX:
import java.util.*;
}
}
EX:
import java.util.*;
LinkedHashSet:
—-------------
Q)What are the differences between HashSet and LinkedHashSet?
—-------------------------------------------------------------
Ans:
—---
1. HashSet was introduced in JDK1.2 version
LinkedHashSet was introduced in JDK1.4 version.
EX:
import java.util.HashSet;
import java.util.LinkedHashSet;
SortedSet:
—-----------
1. It was introduced in JDK1.2 version
2. It is a direct child interface to Set interface.
3. It is not index based.
4. It does not allow duplicate elements.
5. It does not follow the Insertion order.
6. It is mainly for Sorting Order.
7. It does not allow null elements.If we add any null element then
JVM will raise an exception like java.lang.NullPointerException.
8. It does not allow heterogeneous elements, it allows only
Homogeneous elements, if we add any heterogeneous elements then
JVM will raise an exception like java.lang.ClassCastException.
9. If we want to add any element to the SortedSet then that element
must be Comparable Element, that is the element related class
must implement java.lang.Comparable interface, If the element is
not Comparable and if we add that element to the SortedSet then
JVM will raise an exception like java.lang.ClassCastException.
Note: If we want to add a non comparable element to the SortedSet
then we must use Comparator.
Methods:
1. public SortedSet headSet(Object element):
It is able to return a SortedSet object which contains all the
elements which are less than the Specified Element.
EX:
import java.util.SortedSet;
import java.util.TreeSet;
NavigableSet:
—------------
NavigableSet was introduced in Java 1.6 version, NavigableSet is a
child interface to SortedSet interface, it is almost all the same as
the SortedSet but it has defined some methods to perform navigation
over the elements like Getting Descending order of the elements,
Finding ceiling element, floor element , higher element, lower
elements for a particular element.
Methods:
1. public NavigableSet descendingSet():
It can be used to return a NavigableSet object that contains all
the elements in descending order.
EX:
import java.util.NavigableSet;
import java.util.TreeSet;
TreeSet:
—-------
1. It was introduced in JDK1.2 version.
2. It is not a legacy Collection.
3. It is an implementation class to the NavigableSet interface ,
that is it has provided the implementations for all the methods
of the interfaces like Collection, Set, SortedSet and
NavigableSet.
Constructors:
—------------
1. public TreeSet():
It is able to create an empty TreeSet object.
EX:
import java.util.NavigableSet;
import java.util.TreeSet;
[]
EX:
import java.util.*;
class Employee{
}
class Customer implements Comparable{
@Override
public int compareTo(Object o) {
return 100;
}
@Override
public String toString() {
return "Customer";
}
}
}
}
OP:
[AAA, BBB, CCC, DDD, EEE, FFF]
[AAA, BBB, CCC, DDD, EEE, FFF]
[Customer]
str1.compareTo(str2):
1. If str1 comes first when compared with str2 in dictionary
order then compareTo() method will return -ve value.
2. If str2 comes first when compared with str1 in dictionary
order then the compareTo() method will return +ve value.
3. If str1 and str2 are at the same position in the dictionary
order then the compareTo() method will return 0 value.
EX:
import java.util.*;
System.out.println(str1.compareTo(str2));//
abc.cTo(def)==> -3
System.out.println(str2.compareTo(str3));//
def.cTo(abc)==> +3
System.out.println(str3.compareTo(str1));//
abc.cTo(abc)==> 0
}
}
-3
3
0
EX:
import java.util.*;
class Employee implements Comparable{
@Override
public int compareTo(Object o) {
Employee emp = (Employee) o;
int val = this.ename.compareTo(emp.ename);
return val;
}
@Override
public String toString() {
return "Employee{" +
"eno=" + eno +
", ename='" + ename + '\'' +
", esal=" + esal +
", eaddr='" + eaddr + '\'' +
'}'+"\n";
}
}
public class Main {
public static void main(String[] args) {
Employee emp1 = new Employee(111, "Durga", 5000, "Hyd");
Employee emp2 = new Employee(222, "Anil", 6000, "Chennai");
Employee emp3 = new Employee(333, "Raju", 7000, "Pune");
Employee emp4 = new Employee(444, "Pardhu", 85000, "Delhi");
Employee emp5 = new Employee(555, "Balu", 9000, "Mumbai");
Employee emp6 = new Employee(666, "Gopi", 5000, "Goa");
TreeSet ts = new TreeSet();
ts.add(emp1);
ts.add(emp2);
ts.add(emp3);
ts.add(emp4);
ts.add(emp5);
System.out.println(ts);
}
}
@Override
public int compareTo(Object o) {
Employee emp = (Employee) o;
int val = this.eaddr.compareTo(emp.eaddr);
return -val;
}
@Override
public String toString() {
return "Employee{" +
"eno=" + eno +
", ename='" + ename + '\'' +
", esal=" + esal +
", eaddr='" + eaddr + '\'' +
'}'+"\n";
}
}
public class Main {
public static void main(String[] args) {
Employee emp1 = new Employee(111, "Durga", 5000, "Hyd");
Employee emp2 = new Employee(222, "Anil", 6000, "Chennai");
Employee emp3 = new Employee(333, "Raju", 7000, "Pune");
Employee emp4 = new Employee(444, "Pardhu", 85000, "Delhi");
Employee emp5 = new Employee(555, "Balu", 9000, "Mumbai");
Employee emp6 = new Employee(666, "Gopi", 5000, "Goa");
System.out.println(ts);
}
}
If we want to sort all the elements by using Comparable then each and
every element must have sorting logic, that is each and every element
must have compareTo() method, that is each and every element must
implement java.lang.Comparable interface.
To the TreeSet, if we add Non Comparable elements then JVM will raise
an exception like java.lang.ClassCastException.
When we add non comparable elements to the TreeSet then TreeSet will
not have implicit Sorting logic due to the unavailability of
compareTo() method ,in the above context, to sort Non comparable
elements in TreeSet we must provide sorting logic explicitly, here to
provide sorting logic explicitly to the TreeSet we must use
java.util.Comparator.
java.util.Comparator contains the following two methods.
ts.compare(str1,str2)
If str1 comes first when compared with str2 in dictionary order then
compare() method will return -ve value.
If str2 comes first when compared with str1 in dictionary order then
compare() method will return +ve value.
If str1 and str2 are at the same position in the dictionary order then
compare() method will return 0 value.
public TreeSet(Comparator c)
class Test{
public static void main(String[] args){
MyComparator mc = new MyComparator();
TreeSet ts = new TreeSet(mc);
ts.add(e1);
ts.add(e2);
ts.add(e3);
ts.add(e4);
—---
System.out.println(ts);
}
}
EX:
import java.util.Comparator;
import java.util.TreeSet;
class MyComparator implements Comparator{
@Override
public int compare(Object o1, Object o2) {
}
}
EX:
import java.util.Comparator;
import java.util.TreeSet;
class MyComparator implements Comparator{
@Override
public int compare(Object o1, Object o2) {
int val = 0;
if(length1 > length2){
val = 100;
}else{
val = -100;
}
return val;
}
}
public class Main {
public static void main(String[] args) {
StringBuffer sb1 = new StringBuffer("AAAA");
StringBuffer sb2 = new StringBuffer("BBBBB");
StringBuffer sb3 = new StringBuffer("C");
StringBuffer sb4 = new StringBuffer("DDD");
StringBuffer sb5 = new StringBuffer("EE");
MyComparator mc = new MyComparator();
TreeSet treeSet = new TreeSet(mc);
treeSet.add(sb5);
treeSet.add(sb1);
treeSet.add(sb4);
treeSet.add(sb2);
treeSet.add(sb3);
System.out.println(treeSet);
}
}
@Override
public String toString() {
return "Student{" +
"sid='" + sid + '\'' +
", sname='" + sname + '\'' +
", smarks=" + smarks +
'}'+"\n";
}
}
System.out.println(ts);
}
}
EX:
import java.util.Comparator;
import java.util.TreeSet;
@Override
public int compareTo(Object o) {
Student std = (Student)o;
return this.smarks - std.smarks;
}
@Override
public String toString() {
return "Student{" +
"sid='" + sid + '\'' +
", sname='" + sname + '\'' +
", smarks=" + smarks +
'}'+"\n";
}
}
System.out.println(ts);
}
}
Map:
—----
1. It was introduced in JDK1.2 version.
2. It is not a child interface to the Collection interface.
3. It is able to represent all the elements in the form of Key-value
pairs.
4. In Key-Value pairs, both Keys and values are Objects.
5. In key-value pairs, keys must be unique and values may be
duplicated.
6. In Key-Value pairs, keys are not allowing duplicates.
7. In Key-Value pairs, both keys and values are allowing null
elements, where keys are able to allow only one null element, but
values are able to allow more than one null element.
8. In Key-Value pairs, both Keys and values are able to allow
heterogeneous elements.
Methods:
1. public void put(Object key, Object value):
It is able to add the provided key-value in the Map object.
EX:
import java.util.HashMap;
import java.util.Map;
EX:
import java.util.HashMap;
import java.util.Map;
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
EX:
import java.util.HashMap;
import java.util.Map;
}
}
HashMap:
—-------
1. It was introduced in JDK1.2 version.
2. It is not a legacy Map.
3. It is a direct implementation class to Map interface.
Constructors:
—-------------
1. public HashMap():
It can be used to create an empty HashMap object with the
initial capacity 16 elements and with the initial load
factor 75%.
EX:
import java.util.HashMap;
import java.util.Map;
}
}
{}
}
}
{}
}
}
EX:
import java.util.HashMap;
import java.util.Map;
}
}
|Key|Value|hash|next|
EX:
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
EX:
import java.util.*;
IdentityHashMap:
—---------------
Q)What is the difference between equals() method and == operator?
—----------------------------------------------------------------
Ans:
—---
== operator is a comparison operator , it is able to compare the
provided two operands whether the provided operands are the same or
not, here the provided operands may be two primitive values or may be
two object reference values.
EX:
import java.util.*;
class A{
}
public class Main {
public static void main(String[] args) {
int a = 10;
int b = 10;
A a1 = new A();
A a2 = new A();
System.out.println(a1.equals(a2));// false
System.out.println(str1.equals(str2));// true
}
}
true
false
false
false
true
EX:
import java.util.*;
class A{
}
public class Main {
public static void main(String[] args) {
Integer in1 = new Integer(10);
Integer in2 = new Integer(10);
{10=BBB}
{10=AAA, 10=BBB}
WeakHashMap:
—------------
In Java programming , when we create objects as per the requirement,
internally JVM uses a separate component in the form of Garbage
Collector to destroy objects.
Steps:
1. Nullify the object reference to make eligible an object for the
Garbage Collection.
A a = new A();
a = null;
2. Activate Garbage Collector and make the Garbage Collector to
destroy the objects which are not having references.
System.gc();
EX:
import java.util.*;
class A{
A(){
System.out.println("Object Creating......");
}
@Override
protected void finalize() throws Throwable {
System.out.println("Object Destroying.......");
}
}
public class Main {
public static void main(String[] args) {
A a = new A();
a = null;
System.gc();
}
}
Object Creating......
Object Destroying.......
EX:
import java.util.*;
class A{
@Override
public String toString() {
return "A";
}
}
public class Main {
public static void main(String[] args) {
A a = new A();
HashMap hm = new HashMap();
hm.put(a, "AAA");
System.out.println("Before GC: HashMap : "+hm);
a = null;
System.gc();
System.out.println("After GC: HashMap : "+hm);
System.out.println();
A a1 = new A();
WeakHashMap whm = new WeakHashMap();
whm.put(a1, "AAA");
System.out.println("Before GC: WeakHashMap : "+whm);
a1 = null;
System.gc();
System.out.println("After GC: WeakHashMap : "+whm);
}
}
SortedMap:
—----------
1. It was introduced in JDK1.2 version.
2. It is not a legacy Map.
3. It is a direct child interface to the Map interface.
Methods:
1. public SortedMap headMap(Object obj)
It is able to return a SortedMap object containing all the key-
values whose keys are less than the specified key.
NavigableMap:
—-------------
It was introduced in JDK1.6 version, it is a child interface to the
SOrtedMap, it is the same as the SortedMap and it has defined some
methods to perform navigation over the elements.
Methods
1. public NavigableMap descendingMap():
It is able to return a NavigableMap object containing all the
key-value pairs in the keys descending order.
2. public Map.Entry ceilingEntry(Object key):
It is able to return a lower entry among all the entries whose
keys are
greater than or equal to the specified key.
3. public Map.Entry higherEntry(Object key):
It is able to return a lower entry among all the entries whose
keys are
greater than the specified key.
}
}
TreeMap:
—-------
1. It was introduced in JDK1.2 version.
2. It is not a legacy Map.
3. It has provided implementations for all methods of the interfaces
like NavigableMap, SortedMap and Map.
Constructors:
—------------
1. public TreeMap():
It is able to create an empty TreeMap object.
EX:
import java.util.*;
public class Main {
public static void main(String[] args) {
TreeMap treeMap = new TreeMap();
System.out.println(treeMap);
}
}
{}
EX:
import java.util.*;
class A{
}
public class Main {
public static void main(String[] args) {
TreeMap tm = new TreeMap();
tm.put("D", "DDD");
tm.put("A", "AAA");
tm.put("C", "CCC");
tm.put("B", "BBB");
System.out.println(tm);
tm.put("B", "XXX");
System.out.println(tm);
tm.put("E","CCC");
System.out.println(tm);
//tm.put(null, "EEE"); -->
java.lang.NullPointerException
tm.put("F", null);
System.out.println(tm);
//tm.put(10, 100); ----> java.lang.ClassCastException
A a = new A();
//tm.put(a, "YYY"); ---> java.lang.ClassCastException
System.out.println(tm);
}
}
{A=AAA, B=BBB, C=CCC, D=DDD}
{A=AAA, B=XXX, C=CCC, D=DDD}
{A=AAA, B=XXX, C=CCC, D=DDD, E=CCC}
{A=AAA, B=XXX, C=CCC, D=DDD, E=CCC, F=null}
{A=AAA, B=XXX, C=CCC, D=DDD, E=CCC, F=null}
EX: Comparable
import java.util.*;
class Address{
private String hno;
private String street;
private String city;
private String state;
@Override
public String toString() {
return "Address{" +
"hno='" + hno + '\'' +
", street='" + street + '\'' +
", city='" + city + '\'' +
", state='" + state + '\'' +
'}'+"\n";
}
}
class Employee implements Comparable{
private int eno;
private String ename;
private float esal;
@Override
public String toString() {
return "Employee{" +
"eno=" + eno +
", ename='" + ename + '\'' +
", esal=" + esal +
'}';
}
@Override
public int compareTo(Object o) {
Employee emp = (Employee)o;
return -this.ename.compareTo(emp.ename);
}
}
public class Main {
public static void main(String[] args) {
Employee emp1 = new Employee(111, "Durga", 15000);
Employee emp2 = new Employee(222, "Anil", 5000);
Employee emp3 = new Employee(333, "Rakesh", 10000);
Employee emp4 = new Employee(444, "Pardhu", 30000);
}
}
{Employee{eno=333, ename='Rakesh', esal=10000.0}=Address{hno='1145/s-23', street='PS Road',
city='Pune', state='Maharastra'}
, Employee{eno=444, ename='Pardhu', esal=30000.0}=Address{hno='567/e432', street='X Street',
city='New Delhi', state='Delhi'}
, Employee{eno=111, ename='Durga', esal=15000.0}=Address{hno='123/3rt', street='Z Street',
city='Hyd', state='Telangana'}
, Employee{eno=222, ename='Anil', esal=5000.0}=Address{hno='423/1sr', street='MG Road',
city='Chennai', state='Tamilnadu'}
}
EX: Comparator:
import java.util.*;
class Address{
private String hno;
private String street;
private String city;
private String state;
@Override
public String toString() {
return "Address{" +
"hno='" + hno + '\'' +
", street='" + street + '\'' +
", city='" + city + '\'' +
", state='" + state + '\'' +
'}'+"\n";
}
}
class Employee {
private int eno;
private String ename;
private float esal;
@Override
public String toString() {
return "Employee{" +
"eno=" + eno +
", ename='" + ename + '\'' +
", esal=" + esal +
'}';
}
}
class EmployeeComparator implements Comparator{
@Override
public int compare(Object o1, Object o2) {
Employee emp1 = (Employee) o1;
Employee emp2 = (Employee) o2;
return (int)(emp1.getEsal() - emp2.getEsal());
}
}
public class Main {
public static void main(String[] args) {
Employee emp1 = new Employee(111, "Durga", 15000);
Employee emp2 = new Employee(222, "Anil", 5000);
Employee emp3 = new Employee(333, "Rakesh", 10000);
Employee emp4 = new Employee(444, "Pardhu", 30000);
}
}
@Override
public String toString() {
return "Address{" +
"hno='" + hno + '\'' +
", street='" + street + '\'' +
", city='" + city + '\'' +
", state='" + state + '\'' +
'}'+"\n";
}
}
class Employee implements Comparable{
private int eno;
private String ename;
private float esal;
@Override
public String toString() {
return "Employee{" +
"eno=" + eno +
", ename='" + ename + '\'' +
", esal=" + esal +
'}';
}
@Override
public int compareTo(Object o) {
Employee emp = (Employee)o;
return this.ename.compareTo(emp.ename);
}
}
class EmployeeComparator implements Comparator{
@Override
public int compare(Object o1, Object o2) {
Employee emp1 = (Employee) o1;
Employee emp2 = (Employee) o2;
return (int)(emp1.getEsal() - emp2.getEsal());
}
}
public class Main {
public static void main(String[] args) {
Employee emp1 = new Employee(111, "Durga", 15000);
Employee emp2 = new Employee(222, "Anil", 5000);
Employee emp3 = new Employee(333, "Rakesh", 10000);
Employee emp4 = new Employee(444, "Pardhu", 30000);
}
}
{Employee{eno=222, ename='Anil', esal=5000.0}=Address{hno='423/1sr',
street='MG Road', city='Chennai', state='Tamilnadu'}
, Employee{eno=333, ename='Rakesh', esal=10000.0}=Address{hno='1145/s-
23', street='PS Road', city='Pune', state='Maharastra'}
, Employee{eno=111, ename='Durga',
esal=15000.0}=Address{hno='123/3rt', street='Z Street', city='Hyd',
state='Telangana'}
, Employee{eno=444, ename='Pardhu',
esal=30000.0}=Address{hno='567/e432', street='X Street', city='New
Delhi', state='Delhi'}
}
Hashtable:
—---------
Q)What are the differences between HashMap and Hashtable?
—---------------------------------------------------------
Ans:
—----
1. HashMap was introduced in JDK1.2 version.
Hashtable was introduced in JDK1.0 version.
4. HashMap allows only one null element at the keys side and any
number of null elements at the values side.
Hashtable does not allow null elements at both Keys and Values
side. If we add null elements at both Keys and values sides then
JVM will raise an exception like java.lang.NullPointerException.
EX:
import java.util.*;
{A=AAA, B=BBB}
{null=CCC, A=AAA, B=BBB, C=null, D=null}
{A=AAA, B=BBB}
Properties:
—----------
The main purpose of java.util.Properties is to represent the data of a
particular properties file.
abc.properties
—-------------
eno=111
ename=AAA
esal=5000
eaddr=Hyd
import java.io.FileOutputStream;
import java.util.*;
}
}
EX:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.*;
}
}
JDBC Parameters
--------------------------
DriverClass : oracle.jdbc.OracleDriver
Driver URL : jdbc:oracle:thin:@localhost:1521:xe
Db User Name : system
DB Password : durga
Queue:
—------
1. It was introduced in JDK1.5 version.
2. It is a child interface to Collection interface.
3. It is able to follow the FIFO algorithm to manage the elements,
we can change this algorithm in the implementation classes as per
the requirement.
4. It is not index based.
5. It is able to manage the elements as per prior to the process.
6. It allows duplicate elements.
7. It does not follow the Insertion order.
8. It does not follow Sorting order.
9. It does not allow null elements.
10. It allows only Homogeneous elements.
11. It allows only Comparable Elements, if we add non
comparable elements to Queue then JVM will raise an exception
like java.lang.ClassCastException.
Note: If we want to add Non comparable elements to the Queue then
we must use Comparator.
Methods:
1. public void offer(Object obj):
It is able to add the provided element to the Queue.
EX:
import java.util.PriorityQueue;
import java.util.Queue;
EX:
import java.util.PriorityQueue;
import java.util.Queue;
class A{
}
public class Main {
public static void main(String[] args) {
Queue queue = new PriorityQueue();
queue.add(6);
queue.add(2);
queue.add(8);
queue.add(5);
queue.add(2);
queue.add(10);
//queue.add(null); ---> NullPointerException
//queue.add("abc"); --> ClassCastException
System.out.println(queue);
Queue q1 = new PriorityQueue();
//q1.add(new A());----> ClassCastException
System.out.println(q1);
}
}
PriorityQueue:
—-------------
1. It was introduced in JDK1.5 version.
2. It is not a legacy Collection.
3. It is an implementation class to Queue interface.
Constructors:
—-------------
1. public PriorityQueue():
It is able to create an empty PriorityQueue object with the default
initial capacity of 11 elements.
EX:
import java.io.PrintStream;
import java.util.PriorityQueue;
import java.util.PriorityQueue;
import java.util.PriorityQueue;
import java.util.PriorityQueue;
import java.util.SortedSet;
import java.util.TreeSet;
EX:
import java.util.*;
The same process will be repeated when the Head element is processed.
EX:
import javax.xml.stream.events.ProcessingInstruction;
import java.util.*;
import javax.xml.stream.events.ProcessingInstruction;
import java.util.*;
[10, 6, 8, 2, 5, 3]
10
[8, 6, 3, 2, 5]
8
[6, 5, 3, 2]
6
[5, 2, 3]
5
[3, 2]
3
[2]
Methods:
—-------
1. public void addFirst(Object obj):
It is able to add the specified element as First element.
EX:
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
}
}
[CCC, BBB, AAA]
[CCC, BBB, AAA]
EX:
import java.util.ArrayDeque;
import java.util.Deque;
}
}
EX:
import java.util.ArrayDeque;
import java.util.Deque;
public class Main {
public static void main(String[] args) {
Deque deque = new ArrayDeque(3);
deque.addLast("AAA");
deque.addLast("BBB");
deque.offerLast("CCC");
deque.offerLast("DDD");
System.out.println(deque);
System.out.println(deque.getFirst());
System.out.println(deque.peekFirst());
}
}
import java.util.ArrayDeque;
import java.util.Deque;
}
}
null
EX:
import java.util.ArrayDeque;
import java.util.Deque;
}
}
9. public Object removeFirst():
It is able to remove the First Element from the Deque.
EX:
import java.util.ArrayDeque;
import java.util.Deque;
Note: In the above cases, if the specified element does not exist
then JVM will return false value from both the methods.
EX:
import java.util.ArrayDeque;
import java.util.Deque;
}
}
EX:
import java.util.ArrayDeque;
import java.util.Deque;
}
}
EX:
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;
}
}
GGG
FFF
EEE
DDD
CCC
BBB
AAA
ArrayDeque:
—----------
1. It was introduced in JDK1.6 version.
2. It is not a Legacy Collection.
3. It is an implementation class to the Deque interface, it has
provided implementation for all methods of the Collection
interface, Queue interface and Deque interface.
4. It is not index based.
5. It allows duplicate elements.
6. It follows Insertion order.
7. It does not follow Sorting order.
8. It allows heterogeneous elements.
9. It does not allow null elements.
10. Its initial capacity is 16 elements.
11. Its internal data structure is “Resizable Array”.
12. It is not a synchronized Collection.
13. No Method is synchronized in ArrayDeque.
14. It allows more than one thread at a time to access data.
15. It follows parallel execution.
16. It reduces application execution time.
17. It improves application performance.
18. It is not giving guarantees for the data consistency.
19. It is not a threadsafe resource.
Constructors:
—-------------
1. public ArrayDeque():
It is able to create an empty ArrayDeque object with the initial
capacity of 16 elements.
EX:
import java.util.ArrayDeque;
public class Main {
public static void main(String[] args) {
ArrayDeque arrayDeque = new ArrayDeque();
System.out.println(arrayDeque);
}
}
[]
2. public ArrayDeque(int capacity):
It is able to create an empty ArrayDeque with the specified
initial capacity.
EX:
import java.util.ArrayDeque;
public class Main {
public static void main(String[] args) {
ArrayDeque arrayDeque = new ArrayDeque(20);
System.out.println(arrayDeque);
}
}
[]
EX:
import java.util.*;
EX:
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;
System.out.println(deque);
}
}
Collections:
—------------
Q)What is the difference between Collection and Collections?
—------------------------------------------------------------
Ans:
—---
Collection is an interface , it is able to represent a group of other
objects as a single entity.
}
}
2. public static void copy(List dest , List source):
It is able to copy all elements from the source List to
destination List when the destination List size is equal or
greater than the source list size, if the destination list size
is less than the source list size then JVM will raise an
exception like java.lang.IndexOutofBoundsException.
EX:
import java.util.*;
EX:
import java.util.*;
EX:
import java.util.*;
}
}
EX:
import java.util.*;
}
}
}
}
Arrays:
—------
It is an utility class in Collection Framework, it is able to perform
some utility operations over the elements of the Collections.
Methods:
1. public static List asList(Object … elements):
It is able to allow number of elements as input and it will return all
these elements as a List.
EX:
import java.util.*;
EX:
import java.util.Arrays;
10 5 20 15 30 25
5 10 15 20 25 30
EX:
import java.util.Arrays;
import java.util.Comparator;
@Override
public int compare(Object o1, Object o2) {
String str1 = (String) o1;
String str2 = (String) o2;
return str1.length() - str2.length();
}
}
public class Main {
public static void main(String[] args) {
String[] strArray = {"F", "AAA", "EE", "BBBB", "DDDDDD", "CCCCC"};
for(String str: strArray){
System.out.print(str+" ");
}
System.out.println();
Arrays.sort(strArray, new MyComparator());
for(String str: strArray){
System.out.print(str+" ");
}
}
}
EX:
public class Main {
public static void main(String[] args) {
String[] strArray = {"FFF", "AAA", "EEE", "BBB", "DDD", "CCC"};
Arrays.sort(strArray);
System.out.println(Arrays.binarySearch(strArray, "EEE"));
System.out.println(Arrays.binarySearch(strArray, "ZZZ"));
}
}
4
-7
@Override
public int compare(Object o1, Object o2) {
String str1 = (String) o1;
String str2 = (String) o2;
return -str1.compareTo(str2);
}
}
public class Main {
public static void main(String[] args) {
String[] strArray = {"FFF", "AAA", "EEE", "BBB", "DDD", "CCC"};
Arrays.sort(strArray, new MyComparator());
System.out.println(Arrays.binarySearch(strArray, "EEE", new
MyComparator()));
System.out.println(Arrays.binarySearch(strArray, "ZZZ", new
MyComparator()));
for(String str: strArray){
System.out.print(str+" ");
}
}
}
1
-1
FFF EEE DDD CCC BBB AAA