0% found this document useful (0 votes)
12 views94 pages

Strings and Collections

The document discusses the differences between String, StringBuffer, and StringBuilder in Java, focusing on mutability, object creation, and memory management. It covers important methods and constructors for each class, as well as common interview questions related to strings. Additionally, it explains the concept of immutability and provides examples of how to create immutable classes.

Uploaded by

stunning sathvik
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)
12 views94 pages

Strings and Collections

The document discusses the differences between String, StringBuffer, and StringBuilder in Java, focusing on mutability, object creation, and memory management. It covers important methods and constructors for each class, as well as common interview questions related to strings. Additionally, it explains the concept of immutability and provides examples of how to create immutable classes.

Uploaded by

stunning sathvik
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/ 94

Strings:

1> Different between String and StringBuffer


*Mutability vs immutability
2> uString object Creation: Heap and string constant pool
3> Importance of string constant pool
4> Important interview questions of string and stringbuffer
5> important constructors of string class
6> important methods of string class
<>charAt <>concate() <>equals() <>equalsIsIgnoreCase
<>isEmpty() <>length() <>replace() <>substring()
<>indexOf() <>lastindexOf() <>lowercase <>toUpperCase()
<> trim()

7> important conclusions about String immutability

8>creation of our Own immutable class

9>final vs immutability

10>Need of StringBuffer

11>StringBuffer and constructors

12>important methods of stringBuffer

<>length() <>capacity() <>charAt() <>SetCharAt() <>append()

<>insert() <>delete <>deleteCharAt() <>reverse() <>setLength()

<>ensureCapacity() <>trimToSize()

13>Need of StringBuilder

14>Different b/w StringBuffer and stringBuilder

15>string vs String Buffer vs StringBuilder

16>method chaning

1
 difference between String and StringBuffer.

Case 1>in String: once you create String object we can’t change its content
that’s why String is always immutable.
public class string1 {
public static void main(String[] args) {
String ss=new String("nithish");
ss.concat("tulalu");
System.out.println(ss);
}

}
Output: nithish
Case 1>in StringBuffer:
public class string2 {
public static void main(String[] args) {
StringBuffer sn=new StringBuffer("nithish ");
sn.append("tulalu");
System.out.println(sn);
}
}
Output: nithish tulalu

Case2>in String:
public class string3 {
public static void main(String[] args) {
String s1=new String("nithish");
String s2=new String ("nithish");
System.out.println(s1==s2); //false
System.out.println(s1.equals(s2)); //true
}

}
 ‘ == ‘ reference address //always meant for reference compression
 ‘equals ‘ meant for content compression .

Case 2 in StringBuffer:

In String Buffer (.equals() )for reference compression.


public class string3 {
public static void main(String[] args) {
StringBuffer s1=new StringBuffer("nithish");
StringBuffer s2=new StringBuffer ("nithish");
System.out.println(s1==s2); //false
System.out.println(s1.equals(s2)); //false
}

2
String in String class equals () meant for content compression, where us in
StringBuffer equals() meant for reference compression.

String object creation Heap and String constant pool(scp).

 String s=new String (“sahithi”);

Heap String Constant Pool


maintained by JVM , reusability for
s future propose.

sahithi
sahithi

String s= sahithi;

sahithi

Conclusion’s:

Whenever we are using new operator compulsory a new object will be created in
the heap area. That’s why there may be a chance of existing two objects with
same content in the heap area but there is no chance of existing two object
with the same content in the String Content Pool, means in the SCP area for the
same content only one object will be there same object will be reused multiple
time so internally memory will be saved and utilization will be improved.

3
String s1=new String (“Nithish” );

String s2=new String (“Nithish”);

String s3=”Nithish”;

String s4=”Nithish“;

Heap String Constant Pool

Nithish
s3 s4
S1
Nithish

Nithish

S2

String s=new String (“Nithish”);

s.concate(“Tulalu”);

s1=s.concate(“verma”);

total 6 objects will be created 3 in heap area and 3 in SCP.


public class string5 {
public static void main(String[] args) {
String s=new String("Nithish");
s.concat("kumar");
String s1=s.concat(" tulalu");
System.out.println(s);
System.out.println(s1);
}

Output:
Nithish
Nithish tulalu

4
String s1=new String(“spring”);

s1.concate(“fall”);

String s2=new String(“winter”);

s2.concate(“summer”);

sopln(s1);

sopln(s2);

heap Constant String Pool

s1 gc
spring spring

Spring fall

No reference variable fall

s2

Spring winter
winter

no reference variable eligible for gc

Spring winter summer


summer

5
public class string4 {
public static void main(String[] args) {
String s1=new String("you cannot change me");
String s2=new String("you cannot change me");
System.out.println(s1==s2);//false
String s3="you cannot change me";
System.out.println(s1==s3); //false
String s4="you cannot change me";
System.out.println(s3==s4);//true
String s5="you cannot"+" change me";//compile time
System.out.println(s4==s5); //true
String s6="you cannot";
String s7=s6+" change me";
System.out.println(s4==s7); //flase
final String s8="you cannot";
String s9=s8+" change me";
System.out.println(s4==s9); //true

}
Output:
false
false
true
true
false
true
Heap String Constant Pool
s3

uccme uccme

s1 s4

s9
uccme s5

s2

You cannot

s6

uccme

s7
s8

Advantages and important of SCP:

6
>Object can be reused multiple times instead of creating new object.

>same object can be reused memory will be saved performance will be improved.

Disadvantages:

>one reference if any person trying to change then so all the remaining
references will be affected to prevent, JAVA people Introduced immutability
concept.

Example : voting System

Name: Nithish Kumar v1


Father name: Janaki Rao bbsr
Mother name: Jayalaxmi
House no:1525 v2
Street no: ram Nagar 8
Village: paralakhmundi
District: Gajapati v3 pkd
State: Odisha
Pin:761201
vn
Important interview questions .

1>why SCP concept is available only for String object but not for StringBuffer?

>if one person is regular customer to same shop then special privileges given to
him but if this person is go only once a year or month then special privileges not
given to him. That way SCP is available to String but not for StringBuffer.

2>Why String objects are immutable whereas StringBuffer objects are


immutable.

>for String object SCP concept is there so reusability same object is there ,so
if any object value is change then all the reference are affected so immutability
is required.

>in StringBuffer for every reference different object is there because reusing
same object is no there if we change any StringBuffer object it will not
affected other objects because there is no SCP.

7
3>in addition to String objects any other objects are immutable in Java?

>all wrapper class object

>Byte, Short ,Integer, Long, Double, Character ,Boolean

Important constructor of String class;

 String s= new String();


Creates an empty String object.
 String s =new String(String literal);
Create the given String literal How to creates equivalent String.
 String s=new String(StringBuffer sb);
For the given StringBuffer how to creates equivalent String
 String s =new String(StringBullder sb) ;
For given StringBulllder how to create String.
 String s =new String(char[] ch);
For given char[] how to create String objet.
public class String6 {
public static void main(String[] args) {
char [] cc= {'N','I','T','H','I','S','H'};
String s=new String(cc);
System.out.println(s);

byte []b= {97,98,99,100};


String ss=new String(b);
System.out.println(ss);
}

}
Output:
NITHISH
abcd
Important methods of String class:

charAt():The charAt() method returns the character at the specified index in a


String.
public class charat {
public static void main(String[] args) {
String s="Nithish";
System.out.println(s.charAt(5));//s
//System.out.println(s.charAt(10));//error String index out of bound
exception
}
}

8
concate():

The concate() method appends (concatenate) a string to the end of another


String.
public class concate {
//public String concate (String s);
public static void main(String[] args) {
String s="NITHISH";
s=s.concat(" KUMAR");
System.out.println(s);

}
}
Output:
NITHISH KUMAR

equals() :

the equals() method comperes two string and returns true if the strings are
equal ,and false if not.
//public boolean equals (String s);
//public boolean equals (object o);
public class equal {
public static void main(String[] args) {
String s="Nithish";
System.out.println(s.equals("Nithish")); //true
System.out.println(s.equals("nithish"));//false
}

equalsIsignoreCase(): The equalsIsIgonoreCase() method compere two String


,ignoring lower case and upper case differences. This method returns true if
the Strings are equal and false if not .
public class equalsisigonorecase {
public static void main(String[] args) {
String s="Nithish";
System.out.println(s.equalsIgnoreCase("nithish")); //true
System.out.println(s.equalsIgnoreCase("nithish tulalu"));//f
}
}

isEmpty();

The isEmpty() method checks whether a String is empty or not. This

method returns true if the String is empty (length() is 0),and false if not.

9
public class isempty {
public static void main(String[] args) {
String s="";
System.out.println(s.isEmpty()); //true
String ss="nithish";
System.out.println(ss.isEmpty()); //false
String dd=" ";
System.out.println();//false
}

length():The length() method returns the number of character present in the


String. The length() method is suitable for String object but not for arrays.
The length() method can also be used for StringBuilder and StringBuffer
classes.
//public int length
public class length {
public static void main(String[] args) {
String s="rocky randawa";
//length() is applicable for String concept
System.out.println(s.length()); //13

int x[]= {10,20,30,40,50};


//length variable applicable for Array
System.out.println(x.length);//5

}
}

replace(): The replace () method search a string for a specified character ,and
return a new string where the specified(s) are replaced.
//public String replace (char old,char new)
public class replace {
public static void main(String[] args) {
String s="xyyxxyyxxy";
System.out.println(s.replace('x', 'y'));

substring();

The Java String class substring() method returns a part of the string.

10
//public String subString(int begin);
//from begin index to end of substring
public class substring {
public static void main(String[] args) {
String s= "abcdef";
System.out.println(s.substring(3));
// public String subString(int begin, int end)
System.out.println(s.substring(2,4));

IndexOf():The indexOf() method returns the position of the first occurrence


of specified character(s) in a string.
//public int indexOf(char[]ch)
public class indexof {
public static void main(String[] args) {
String s="NITHISH";
System.out.println(s.indexOf('S'));//5
System.out.println(s.indexOf('M'));//-1
}

lastindexOf():
//public int lastIndexOf( 'char')

public class indexof {


public static void main(String[] args) {
String s="NITHISH";

System.out.println(s.lastIndexOf('I'));
}

}
tolowercase():

The toLowerCase() method converts a String to lower case letters.


public class tolowercase {
public static void main(String[] args) {
String s="TULALU NITHISH KUMAR";
System.out.println(s.toLowerCase());
}

4}
Op: tulalu nithish kumar

11
toUpperCase():

The toUpperCase() method converts a string to upper case letters.


public class tolowercase {
public static void main(String[] args) {
String s="tulalu nithish kumarR";
System.out.println(s.toUpperCase());
}

}op: TULALU NITHISH KUMAR

Trim():The Java String trim() method is used to remove leading and trailing
whitespace from a string.
public class tolowercase {
public static void main(String[] args) {
String s=" TULALU NITHISH KUMAR ";
System.out.println(s.trim());
}

} op: TULALU NNITHISH KUMAR

import java.util.Scanner;

public class nithish {


public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String name=sc.nextLine().toLowerCase().trim();
if (name.equals("anime")) {
System.out.println("naruto and onepice");
}
else if( name.equals("character")){
System.out.println("monky d lufi");

}
else if(name.equals("dark anime")) {
System.out.println("death_note");
}
else {
System.out.println("not valied input");
}
}
}

Important constants about String immutability.

12
public class string_constructor {
public static void main(String[] args) {
String s=new String("china swami");
String s1=s.toUpperCase();
String s2=s.toLowerCase();
System.out.println(s==s1);//false
System.out.println(s==s2);//true
}

Heap String Constant Pool

S1 China swami
China swami

S2

CHINA SWAMI

S3

public class stringConstructor {


public static void main(String[] args) {
String s1="swami";
String s2=s1.toString();
String s3=s1.toLowerCase();
String s4=s1.toUpperCase();
System.out.println(s1==s2);//true
System.out.println(s1==s3);//true
System.out.println(s1==s4);// false
}

13
Creation of our own immutable class.
package basic_problems;
//make class as final
//make varaiable as private
//make variable as final
//no setter method
public class immuatable {
private int i;
immuatable(int i){
this.i=i;
}
public immuatable modify(int i) {
if(this .i==i) {
return this;

}
else {
return new immuatable(i);
}

}
public static void main(String[] args) {
immuatable i=new immuatable(10);
immuatable in= i.modify(100);
System.out.println(i==in);
System.out.println(i==in);

}
}

Final:
public class finall {
public static void main(String[] args) {
final StringBuffer sb=new StringBuffer("Nithish");
sb.append("Tulalu");
System.out.println(sb);

}
}

>even the reference variable is final still in this StringBuffer object we are
allowed to chance the content , means that by declaring reference variable as
the final we are not going to get immutably nature.

>means we cant reassign the reference variable to new object.

14
StringBuffer and StringBulider questions.

1. public class qustions {


public static void main(String[] args) {
String ta="A";
ta.concat("B");
String tb="C";
ta=ta.concat(tb);
ta.replace("C", "D");
ta=ta.concat(tb);
System.out.println(ta);
}

}
> ABCD
>ACD
>ACC (ANSWER)
>ABD

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


String str="";
str.trim();
System.out.println(str.equals(" "));
System.out.println(str.isEmpty());
}

}
> true true
> false false
>true false
>false true (answer)

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


String s="nithish tulalu";
int len=s.trim().length();
System.out.println(len);

}
}

>12
>13
>55
>14 answer

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


String s="hello world";
s.trim();
int i=s.indexOf(" ");
System.out.println(i);

}
} 5

15
Needs of StringBuffer:

If the content is not fixed and keep on changing String concept never
recommended to use.

StringBuffer:

All the respect changes will be perform in existing only.

S---------- Nithish --------------------------------------- Nithish kumar

s.concate(“kumar”)

Nithish kumar Tulalu


s.concate(“Tulalu”)

s.concate(“Sir”) Nithish Kumar Tulalu Sir

StringBuffer Class Constructor:

 StringBuffer sb =new StringBuffer(“Nithish”);


 StringBuffer sb=New StringBuffer();
Default capacity =>16
For extra capacity
New capacity=(cc+1)*2=34
For more capacity=(34+1)*2=70

1
public class refere {

public static void main(String[] args) {


StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity()); //16 default
System.out.println(sb.length());//0
sb.append("abcdefghijklmnopqrst");
System.out.println(sb.capacity());//34
}
}

16
2public class refere {
public static void main(String[] args) {
StringBuffer sb=new StringBuffer(100);
System.out.println(sb.capacity()); //100
}

3>StringBuffer sb=new StringBuffer(String s);

For the given equivalent StringBuffer object will be created.

4>StringBuffer sb=new StringBuffer(“Nithish”);

Capacity=s.length(); 16+7

Sysout(capacity) /23

Important method of StringBuffer class:

append() : The append() method concatenates the given argument with this
String.
public class append {
public static void main(String[] args) {
StringBuffer sb=new StringBuffer("Nithish");
System.out.println(sb);//Nithish
sb.append(" Tulalu");
System.out.println(sb); //Nithish Tulalu
}

Length //charAt//setCharAt//Capacity
public class lenht {
// public int length()
// public int capacity()
// char At()

public static void main(String[] args) {


StringBuffer sb=new StringBuffer("Java");
System.out.println(sb.charAt(2)); //v
// System.out.println(sb.charAt(30)); exception
System.out.println(sb.length());//4
System.out.println(sb.capacity());// 16+4 =20
sb.setCharAt(1, 'f');
System.out.println(sb);//Jfva

}
}

17
Insert(): The insert() method the given String with this at the give position.
public class insert {
public static void main(String[] args) {
StringBuffer sb=new StringBuffer("Nithish Kumar");
sb.insert(5, "ram parvu");
System.out.println(sb);//Nithiram parvush Kumar
}

}
Replace (): The replace() method replace the given string from the specified
beginIndext and endIndex.
public class replac {
public static void main(String[] args) {
StringBuffer sb=new StringBuffer("Nithish");
sb.replace(0, 7, "Vamshi");
System.out.println(sb); //vamshi
}

Delete charAt():
public class ff {
public static void main(String[] args) {
StringBuffer sb=new StringBuffer("Nithish Kumar Tulau ");
sb.deleteCharAt(5);
System.out.println(sb);Nithih Kumar Tulalu
}

}
Reverse():
public class reverse {
public static void main(String[] args) {
StringBuffer sb=new StringBuffer("nithish kumar atulalu");
sb.reverse();
System.out.println(sb); //ulaluta ramuk hsihtin

}
Set length():
public class setlen {
public static void main(String[] args) {
StringBuffer dd=new StringBuffer("Nithish kumar");
dd.setLength(5);
System.out.println(dd); //Nithi
}

18
Ensure capacity:
package basic_problems;
//public void ensure capacity(int capacity)
public class ensurecapacity {
public static void main(String[] args) {
StringBuffer sb= new StringBuffer();
System.out.println(sb.capacity());//16
sb.ensureCapacity(10000);
System.out.println(sb.capacity());//10000

}
}
Trim to size():
public class trim {
public static void main(String[] args) {
StringBuffer sb=new StringBuffer(1000);
System.out.println("ABC");
sb.ensureCapacity(sb.capacity());
sb.trimToSize();
System.out.println(sb); //ABC
System.out.println(sb.capacity());//0
}

Delete();
//public sb delete(int begen int end)
//from begin index to end -1 index
public class delete {
public static void main(String[] args) {
StringBuffer sb=new StringBuffer("abcdefgh");
sb.delete(2, 5);
System.out.println(sb); //abfgh

}
}
Method Chaining:

Method chaining is a common syntax for invoking multiple method calls in


object-oriented programming languages. Each method returns an object,
allowing the calls to be chained together in a single statement without requiring
variables to store the intermediate results.
public class chaining {
public static void main(String[] args) {
StringBuffer sb=new StringBuffer();
sb.append("Nithish").append("Kumar").replace(2, 4,
"hhh").reverse();
System.out.println(sb);
}

19
StringBuffer StringBuilder
>>every method present in >>no method present in StringBuilder is
StringBuffer is synchronize. Synchronize.
>>At a time only one thread is allowed >>at a time multiple threads are
to operate on StringBuffer object and allowed operate on StringBuilder
hence it is thread safe. object hence it not thread safe.
>>thread are required to wait to >>thread are not required to wait to
operate on StringBuffer object and operate on StringBulider object and
hence relatable slow. hence relatable high.
>>introduced in 1.0 version >>introduced in 1.5 version.

String: if the content is fixed if it doesn’t change frequently highly recommend


to go for String concept and hence it is also thread safe.

StringBuffer: if the content is not fixed and keep on changing highly


recommend to go for StringBuffer but thread safety required , means only one
thread allowed at a time.

StringBuilder: content is not fixed and keep on changing if I don’t want thread
safety ,multiple thread are allowed to operate at a time on object then
recommend to go for StringBuilder.

Non-primitive datatype

With respect to datatypes we have to classifications primitive datatype and


non-primitive datatypes.

Again in primitive datatypes are 8 types classification.

Primitive datatypes are applicable for storing decimal, non-decimal ,symbols ,and
true false value and they are available in the form of keywords they have fixed
range and capacity.

When it’s come to storing hexadecimal values(object-info) all the primitive


datatype will failed to store them so hence we make use of non-primitive
datatypes to store hexadecimal value or object information.

Non-primitive datatype are available in the form of class ,interface and Array
where they don’t have fixed range and capacity .

Non-primitive datatype can be pre-define as well as user define.

20
Q1>create a class Bike define two properties name and price initialize using
constructor create minimum 3 object and store them in an array print the
details using for loop.
package basic_problems;

public class Bike {


String Bike_name;
int Bike_Price;
String model;
Bike(String name,int Price,String model){
this.Bike_name=name;
this.Bike_Price=Price;
this.model=model;

}
public static void main(String[] args) {
Bike b1=new Bike("hero",1000,"splnder");
Bike b2=new Bike("honda",1000,"city");
Bike b3=new Bike("ktm",10000,"rc200");
Bike obj[]= {b1,b2,b3};
for(int i=0;i<obj.length;i++) {
System.out.println(obj[i].Bike_name+" "+obj[i].Bike_name+"
"+obj[i].model);

Output:
hero hero splnder
honda honda city
ktm ktm rc200

Q2>create a class employee two properties name ,salary initialize using


constructor create minimum 3 object stores them in an array print the details
for each object using for loop calling details method.

21
public class employee {
String name;
int salary;
employee(String n,int s){
this.name=n;
this.salary=s;

}
void detailes() {
System.out.println(this.name + " "+this.salary);
}

public static void main(String[] args) {


employee e1=new employee("sai kumar",10000);
employee e2=new employee("rajesh ",100);
employee e3=new employee("pavan",10);

employee []x= {e1,e2,e3};


for(int i=0;i<x.length;i++) {
x[i].detailes();
}
Output:
sai kumar 10000
rajesh 100
pavan 10

ToString() Method:

>>we can use toString() to get String representation of an object.

String s= o .toSting()
obj

Sysout(s); Sysout(s.toString());

String s=obj.toString();

>> Whenever we are trying to print object reference internally toString() will be
called.
class Student{

22
String name;
int marks;
public Student(String name, int marks) {

this.name = name;
this.marks = marks;
}
}

public class demoo {


public static void main(String[] args) {
Student s1=new Student("nithish ",995);
Student s2=new Student("vamshi",999);
System.out.println(s1);
System.out.println(s1.toString());
System.out.println(s2);
}

}
Output:
basic_problems.Student@133314b
basic_problems.Student@133314b
basic_problems.Student@b1bc7ed

>>if one class contain toString() then Object class toString() will be executed.

Public String toString() {

return getClass.getName()+”@”+integertoHexString(hashCode());

>>in the above example ,object class toString() got executed which is
implemented as follows.

>>in all wrapper class , collection classes ,String class ,StringBuffer class and
StringBuilder class toString() method is overridden for meaningful String
representation. Hence it is highly recommended to override toString() method

In our class also

class students{
String name;
int marks;
public students(String name, int marks) {

this.name = name;
this.marks = marks;
}
@Override
public String toString() {
return "students_name=" + name + ", marks=" + marks ;
}

23
}
public class demo4 {
public static void main(String[] args) {
students s =new students("nithish kumat",451);
students s2=new students("nithish kumat",451);
System.out.println(s);
System.out.println(s2);
System.out.println(s.toString());
}

}
Output:
students_name=nithish kumat, marks=451
students_name=nithish kumat, marks=451
students_name=nithish kumat, marks=451

Heterogeneous array:

1> Create a class Bike define two properties name, color and initialize using
constructor and override toString() method. Create a class car define
properties brand ,price and initialize using constructor and override
toString() method. Create minimum 3 objects for each class and store all
the objects inside same array print the details of each object using for
loop.

package basic_problems;
class bike{
String name;
String color;
public bike(String name, String color) {

this.name = name;
this.color = color;
}
@Override
public String toString() {
return "bike [name=" + name + ", color=" + color + "]";
}
}
class Car{
String brand;
int price;
public Car(String brand, int price) {

this.brand = brand;
this.price = price;
}
@Override
public String toString() {
return "car [brand=" + brand + ", price=" + price + "]";
}

24
}
public class demo {
public static void main(String[] args) {
bike b1=new bike("hero"," red-green");
bike b2=new bike("honda"," black-red");
bike b3=new bike("tvs","white-blue");
Car c1=new Car("honda-city",1200000);
Car c2=new Car("hynday-i10",450000);
Car c3=new Car("audi q8",8000000);
Object[]x= {b1,b2,b3,c1,c2,c3};
for(int i=0;i<x.length;i++) {
System.out.println(x[i]);

}
}

Generalization:

>>it is the process of providing a common datatype or common category for


multiple different objects.

>>we can have a different user defines generalized datatype as well as


predefined generalized datatype.

>>any parent class datatype can become user defined generalized datatype.

Object Object

Car Bike watch

Predefined

Fossils Fastrack titan

User define

Create a class Mobile define properties model ,color override toString() and
define a class OnePlus and inherit properties from mobile define a class relame

25
and inherit properties Store all the objects in same array .print details for each
object using for loop.
package nithish;
class mobile{
String model;
String color;
@Override
public String toString() {
return this.model+" "+this.color;
}

}
class oneplus extends mobile{

}
class realme extends mobile{

}
public class demooo {
public static void main(String[] args) {
oneplus o1=new oneplus();
o1.model="oneplus 7";
o1.color="blue";
realme r1=new realme();
r1.model="realme 6 pro";
r1.color="blue";
mobile []tt= {o1,r1};
for(int i=0;i<tt.length;i++) {
System.out.println(tt[i]);
}
}

Output:
oneplus 7 blue
realme 6 pro blue

>>representing multiple different by a common type category is called


generalizations.

>>in java generalization can be achieved using inheritance.

>>Super class is generalized from of sub class.

>>Sub class is specialized from of super class.

General class: Loosely speaking a class which tells the main function but not
the specific details the class situated at the top of the inheritance hierarchy
can be general.

26
Specific class:-A class which is very particular and states the specifics details.
The lass situated at the bottom of the inheritance hierarchy can be said as
specific.

 Lemon and orange are more specific than citrus.


 Banana and Apple are more specific than non-citrus.
 Citrus and non-citrus are more specific then fruit.
 Fruit is most general class.

Wrapper Classes:

>>Object array is a special type of array which is capable of storing any data.

>>with respect to Object array ,when we add any primitive data, they will be an
automatic conversion from primitive to non-primitive. Where internally wrapper
classes will be used but this feature is not available from the older version of
JDK{1.4v}

>>So, hence we need to manually convert the primitive data to non-primitive


.This can be achieved by using wrapper classes.

>>wrapper classes are a set of inbuilt classes present in java.lang package which
helps in converting the data from primitive to non-primitive and vice versa.

27
Primitive Datatype Wrapper classes
byte Byte
short Short
int Int
long Long
float Float
double Double
boolean Boolean
char Character
byte b=10;

Byte wb=new Byte(b);


package nithish;

public class dddddddd {


public static void main(String[] args) {
byte b=10;
short s = 100;
int i = 1000;
long l = 1000000L;
float f = 10.0f;
double d = 100.0;
char c = 's';
boolean x = false;
Byte wb = new Byte(b);
Short ws = new Short(s);
Integer wi = new Integer(i);
Long wl = new Long(l);
Float wf = new Float(f);
Double wd = new Double(d);
Character wc = new Character(c);
Boolean wx = new Boolean(x);
Object[] z = {wb,ws,wi,wl,wf,wd,wc,wx};
for (int j = 0; j < z.length; j++) {
System.out.println(z[j]);
}
}
}
10
100
1000
1000000
10.0
100.0
s
false

28
Collection Framework:
Variables limitations in array
√--------------------- <> fixed in size

int x=10; <> homogeneous


int y=20; <> No Underlying data structure
int z=30;
Arrays
------------------

Student [] s=new[1000];
S[0]=new Student(); (√)
S[1]=new Customer(); error: incompatible found: customer required :Student

>> An array is an indexed collection of fixed number of homogeneous data


elements.

>>The main advantage of Array is we can represent multiple values by using


Single variable. So that readability of the code will be improved.

Limitations of Arrays:

>> Array are fixed in size . i.e. once we create an Array there is no chance of
increasing or decreasing the size based on our requirement. Due to this , to use
Arrays concept compulsory we should know the size in advance. Which may not
be possible always.

>>Array can hold homogenous datatype elements.

We can solve this problem by using object type array

Object [] a= new Student ();

a[1]=new Customer ();

>>Arrays concept is not implemented based on some standard data structure and
hence ready-made method is not available for every requirement. We have to
write code explicitly which increase complexity of programming.

>>To overcome above problem of Arrays , we should go for collections concept.

29
<1>Collections:

>>collections are growable in nature I .e., Based on our requirement we can


increase or decrease the size.

>>Collections can hold both homogenous and heterogeneous elements objects.

>>Every collection class is implemented based on some standard Data Structure


hence for every requirement we have to write code explicitly which increases
complexity of the program.

>>being a programmer ,we are responsible to use those methods, we are not
responsible to implement those methods .

Difference between Arrays & Collections:

Arrays Collections
Arrays are fixed in size that is once it is growable in nature that is based
crated we cannot increase or decrease on our requirement we can increase or
Array size based on our requirement. decrease the size with respect to
memory . Collections are recommended.
With respect to memory point of view with respect to memory collections are
Array are not recommended to use. recommended to use
performance wise Array are is performance wise collections are not
recommended to use. recommended to use
Arrays are homogeneous Collections are both heterogeneous
and Homogeneous
There is no underlying data Structure Every collection class is implemented is
(readymade method) we have to write based on some standard data
code explicitly which increases structure. It consists of readymade
complexity of the program methods.
Arrays can hold primitives and objects Collection can hold object but not
primitives.

Individual object
S1 s2 Single entity

S3 s4
If we want to represent group of individual
S5
objects as a single entity then we should go for
collection

30
Collection Framework:

>>it contains several classes and interfaces which can be used to represent
group of individual objects as a single entity.

Java C++
Collection STL(Standard Template
Collection Library)
Framework

Key interfaces of Collections framework:

Collection List Set

SortedSet NagvigableSet Queue

Map Sortedmap NavigableMap

Collection (i) //Collection interface

>>if we want to represent a group of individual objects as a single entity then we


should go for Collection(I).

>>Collection interface defines the most common methods which are defined for
any collection object.

>>in general collection interface is considered as root interface for collection


framework

>>there is no concreate class which implements collection interface directly.

Difference between Collection and Collections :

Collection Collections
Collection is an interface which can be It is a utility class present in java.util
used to represent a group of individual package to define several utility
objects as a single entity. methods. Like sorting and searching
etc., for collection object.

31
<2>List(i):

>> list is the child interface of collection.

>>if we want to represent a group of individual object as a single entity where


duplicates are allowed and insertion order must be preserved then we should
go for list.

Collection(i) 1.2 version

List(i) 1.2 version


Re enringing(1.2 v)
Vecter
Implementation class

Array List(1.2 version) LinkedList(1.2 version) Stack

Note: in 1.2 version vector and stack classes are modified to implement list
interface.

<3>Set(i):

Collection (i) 1.2 v

Set (i) 1.2 v

HashSet 1.2v
first implement classes

 Second implement Classes


Linked HashList 1.4 v

32
 It is the child interface of collection.

if we are representing a group of individual objects as a single entity where


duplicates are not allowed and insertion order not required. Then we should go
for Set(i).

<4>SortedSet(I):

it is the child interface of Set(i).

if we want to represent a group of individual object as a single entity where


duplicate are not allowed and all object should be insertion according to same
shorting order then we go for ShortedSet(I).

Collection(I) 1.2 v

Set(i) 1.2 v

SortedSet(i) 1.2 v

NagviableSet(i) 1.6v

TreeSet (implement classes)(1.2 v)

33
<5>NagvigableSet(i):

NagvigableSet(i) it is the child interface of Sorted Set.

it contains several methods for Navigation purpose.

Difference between list and Set :

List(i) Set(i)
 Duplicates are allowed duplicates are not allowed
insertion order preserved insertion order not preserved

<6> Queue(i)

it is a child class interface of Collection(i)

if we want to represent a group of individual object prayer to processing.

usually Queue follows FIFO(first in first out) but based on our requirements
we can implement our own payrate order.

Example: Before sending a mail all mail id’s we have to store in some data
Structure in which order we added mail ids in the same only must should be
delivered for the requirements Queue is best choice.

34
Note: All the above interface (Collection ,List ,Set ,ShortedSet , NavigableSet

Queue) meant for represent a group of individual object where as if we want to


represent a group of object as key value pairs then we should go for map.

MAP:

Map is not the child interface of collection if we want to represent a group of


individual objects as key value pair the we go for map.

Key Value
Sno Name
1 Nithish
2 Kumar Swami
Both key and value are objects only duplicate keys are not allowed but not
allowed but value can be duplicate

ShortedMap:

It is the child interface of MAP if we want to represent a group of individual


object as key value pairs according to shorting order of keys then we should go
for ShortedMap.

In ShortedMap the Shorting should be based in key but not based on values .

Map(i) 1.2 v

ShortedMap(i) 1.2v

35
Navigable Map(i) :

>> it is the child interface of Sortedmap.

>> it defines several utility methods for navigation methods.

36
Comparator, Comparable & Cursor :

 if you want default natural sorting order in that case , we use


Comparable(i).
 if you want customized Sorting order in that case , we use Comparator(i)
 if we want to get objects one by one from collection then we should go
for cursors. Cursors are further classified into three types:
1.Enumeration Legacy Character
2. Iterator(l)
3.listIterator(i)

<> if you want utility ck=lasses

1.Collections

2.Arrays

Legacy characters:

 the following are legacy characters parent in collection framework:


1.Enumeration
2.Dictionary (Abstract Class)
3.Vector(implement class)
4.Stack(implement class)
5.Hashtable(implement class)
6.properties(implement class)

Interview Questions:

1.Difference between Collection and Collections.

Collection Collections
Definition It is an interface that forms This utility class provides
the root of the java collection static methods to perform
framework. operations on collections.
Usage Act as an interface for other This class offers utility
interfaces like list, set and functions that operate on or
Queue. Some of the common return collections. For
methods include add() example ,the
,remove() ,size() . Collections.sort() method
sorts elements in a list.
Implementation It doesn’t have any direct As it is a final class, meaning
implementation as it is an it cannot be subclassed.
interface .

37
But you can implement the It doesn’t have any public
collection interface by using constructors so its doesn’t
various java classes ,like have any public constructor
ArrayList, HashSet and so its method are accessed
priorityQueue. statically
Flexibility Since it’s an interface, As a utility class, it provides
developer can create custom ready-to-use methods that
implementation if required. help the developer to save
time while performing
common operations on
collections.
Purpose The purpose is to provide a It offers a utility function
standard way to handle and that simplifies common tasks
manage a group of objects. associated with collections.

2.Difference between List & Set

List Set
Indexing It supports indexing, that is It doesn’t support indexing
indexed sequence. that is the set is a non-
indexed sequence
Order It maintains the order of It doesn’t maintain the order
the element of the element
Duplicates Duplicate values are allowed Set always contains the
in the list. unique vale ,i.e. it does not
contain any duplicate value.
Null Element Multiple null values can be Only one null value can be
stored stored
Positional Access Yes No
Mutable Yes, list element can be Yes ,sets elements can be
modified. modified.
Use Cases Suitable for sequence, Suitable for storing
ordered data unordered data

3. Difference between Collection & Map.

38
<> Collection Vs Collections:

Collections interface defines the most common methods which are applicable
for any collection object.

Example: methods area

 Boolean add(Object o);


 Boolean addAll(Collection C);
 Boolean remove(object o);
 Boolean removeAll(Collection C);
 Boolean retainAll(Collection C);  to remove all object except those
parent in c.
 Void clear();
 Boolean Contains(object 0);
 Boolean ContainAll(Collection c);
 Boolean is Empty();
 Int size();
 Object [] toArray();
 Iterator iterator();

There is no concreate class which implements collection interface directly.

List vs Collection: -

List is a child interface of Collection.

If we want to represent a group of objects as a single entity where duplicates


are allowed and insertion order must be preserved then we should go for List.

We can preserve insertion order via index or with index and we can
differentiate duplicate objects by using index. Hence, index will play an
important role in List.

List Interface also has its own specific methods. They are: -

 void add(int index, Object O);


 boolean addAll(int index, Collection C);
 Object get(int index);
 Object remove(int index);
 Object set(int index, Object new);

To replace the element present at specific index with provided objects and
returns old object.

39
 int indexOf(Object O);
 ListIterator listIterator();

Array list:

 The underlying Data structure is resizable array or growable array.


 Duplicates are allowed
 Insertion order is preserved
 Heterogenous object are allowed (Except TreeSet & TreeMap)
everywhere heterogeneous object are allowed.
 Null insertion is allowed

Constructor:

<1>ArrayList l=new ArrayList();

 Creates an empty Array list objects with default initial capacity 10, once
Array list reaches its maximum capacity then a new array list object will
be created with given default capacity 10.

new capacity=(Current capacity *3/2)+1

10*3/2+1=16
11 th object
* * * * * * * * * *
0 1 2 3 4 5 6 7 8 9

* * * * * * * * * * *

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

40
<2> ArrayList l=new ArrayList(int initial Capacity);

create an empty ArrayList object with specified initial capacity

<3> ArrayList l=new ArrayList(Collection c);

create an equivalent ArrayList object for given collection.


package basic_problems;

import java.util.ArrayList;

public class fixering {


public static void main(String[] args) {
ArrayList<Object>l=new ArrayList<>();
l.add("nithish");
l.add(10);
l.add("A");
l.add(null);
l.add("kumar");
System.out.println(l);
l.remove(2);
System.out.println(l);
l.add(2,20);
System.out.println(l);
l.add(5,"tulalu");
System.out.println(l);

}
}
Output:
[nithish, 10, A, null, kumar]
[nithish, 10, null, kumar]
[nithish, 10, 20, null, kumar]
[nithish, 10, 20, null, kumar, tulalu]

Usually we can use collection to hold and transform object from one location to
another location( container) to provide for this requirements collection class by
default implementation Serializable and interface.

ArrayList and vector class implements random access interface so that any
random elements we can access with same speed.

Random Access:

Random Access interface present in{ java.util } package and it doesn’t contains
any method it is marker interface where required ability will be provided
automatically by the jvm.

ArrayList is the best choice if our frequently operation is retable operation is


retriable operation because array list implements random access interface.

41
package basic_problems;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.RandomAccess;

public class thum {


public static void main(String[] args) {
ArrayList l1=new ArrayList();
ArrayList l2=new ArrayList();
System.out.println(l1 instanceof Serializable);
System.out.println(l2 instanceof Serializable);
System.out.println(l1 instanceof RandomAccess);
System.out.println(l2 instanceof RandomAccess);
}
}
Output:
True
True
True
True
Array is the worst choices if our frequent operation is insertion or deletion in
the in the middle.

a b c e
 Array l

l.add(3,”m”);

a b c m e
Difference between ArrayList and vector

ArrayList Vector
Every method presence in ArrayList is Every method presence in vector is
non-synchronize. synchronize.
At a time multiple thread are allowed At a time only one thread are allowed
to operate an array list object and to operate an vector object and hence
hence it is not thread safe. it is thread safe.
Relatively performance is high because Relatively performance is low because
thread are not required to wait to thread are not required to wait to
operate on ArrayList object. operate on ArrayList object.
Introduced in 1.2 version Introduced in 1.0 version
Means non legacy Means it is legacy

42
How to get synchronized version of array list object.

By default ArrayList is non-synchronized but we can get synchronized version


ArrayList object by using SynchronizedList() of collection class.

public Static List synchronizedList(List i) ;

Example:

ArrayList l =new ArrayList();

List l=collections.SynchronizedList(i);

Synchronized non-synchronized

Similarly we can get synchronized version of set and map objects by using the
following methods of collections class.

public static set synchronizedSte (set s) ;

 public static map synchronizedMap (map m) ;

LinkedList:

The underlying Data Structure is double linklist //circular list.

Double linklist

A B C

 Insertion order is persevered.


 Duplicate objects allowed
 Heterogenous object allowed
 Null insertion is possible
 Linkedlist implements Serializable and cloneable interfaces But not
random access.

43
 Linkedlist is best Choice if our frequent operation is insertion or deletion
In the middle.
 Linked list is the worst choice if our frequent operation is retriable.

Constructor:

LinkedList l=new Linkedlist();

create an empty Linkedlist object

LinkedList l=new Linkedlist(collection c);

create an equivalent LinkedList object for the given collection.

LinkedList Specific methods:

 void addfirst (object o);


 void addlast (object o);
 object getfirst ();
 object getlast ();
 object removeFirst ();
 object removelast ();

import java.util.LinkedList;

public class linklistdemo {


public static void main(String[] args) {
LinkedList<Object> l=new LinkedList<>();
l.add("Nithish");
l.add(30);
l.add(null);
l.add("kumar");
l.set(0, "Tulalu");
l.set(1, "NIthish");
l.set(2, "Kumar");
System.out.println(l);
l.removeLast();
System.out.println(l);
}

Output:
[Tulalu, NIthish, Kumar, kumar]
[Tulalu, NIthish, Kumar]

44
Difference between ArrayList and LinkedList.

ArrayList LinkedList
ArrayList is the best choice if our LinkedList is the best choice if our
frequent operation relivable frequent operation is insertion or
operations. deletion in the middle.
ArrayList is the worst choice if our LinkedList is the worst choice if our
frequent operation is insertion or frequent operation relivable
deletion in the middle operations.
in ArrayList the element will be in Linkedlist the element will not be
element will be stored in conjunctive stored in conjunctive memory location
and hence retrieval option is easy. and hence retrieval option will be
complex.

Vector:

The underlying Data Structure is resizable Array or growable Array.

 Insertion order is preserved.


 duplicate are allowed
 heterogenous object are allowed
 null insertion is possible.
 It implements serializable and cloneable and random access interface
 Every method present in vector is synchronized and hence vector object
are thread safe

Constructor:

1>vector v=new vector();

Create an empty vector object with default capacity 10

Once vector reaches its max capacity then a new vector object will be created
with new capacity

 new capacity= current capacity *2

2>vector v =new vector(int initial capacity);

Creates an empty vector object with initial capacity

45
3>vector v =new vector (int initial capacity ,int incremental capacity)

When capacity is full it creates a new object with the specified capacity.

4>Vector v =new Vector(Collection c);

Creates a equivalent vector object for the given collection .this vector object is
meant for inter conversion between collection objects.

Vector specific method:

1>To add objects:

 add(Object o);Collection
 add(int index, Object o) list
 add Element(Object o);Vector

2>To remove object:

 remove (Object 0);Collection


 removeElement(Object o);vector
 remove(int index);list
 removeElementAt(int index);vector
 clear();collection
 removeAllElement();vector

3>To get Object:

 Object get(int index);list


 Object elementAt(int index);vector
 Object firstElement();vector
 Object lastElement();vector

4>other objects:

 int size();
 int capacity();
 Enumeration element();

Default capacity:
package basic_problems;
import java.util.Vector;
public class vectordemo {
public static void main(String[] args) {
Vector v=new Vector();
System.out.println(v.capacity());

46
for(int i=0;i<=10;i++) {
v.addElement(i);
}
System.out.println(v.capacity());
v.addElement("A");
System.out.println(v.capacity());
System.out.println(v);
}

}
Output:
10
20
20
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, A]

package basic_problems;

import java.util.Vector;

public class vectordemo {


public static void main(String[] args) {
Vector v=new Vector(24);
System.out.println(v.capacity());
for(int i=0;i<=10;i++) {
v.addElement(i);
}
System.out.println(v.capacity());
v.addElement("A");
System.out.println(v.capacity());
System.out.println(v);
}
}
Output:
24
24
24
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, A]
==========================================================================
package basic_problems;

import java.util.Vector;

public class vectordemo {


public static void main(String[] args) {
Vector v=new Vector(10,5);
System.out.println(v.capacity());
for(int i=0;i<=10;i++) {
v.addElement(i);
}
System.out.println(v.capacity());
v.addElement("A");
System.out.println(v.capacity());
System.out.println(v);
}
}
10
15
15

47
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, A]

Stack:

It is a child class of vector.

It is a specially designed class for last in first out order(LIFO).

Constructor of stack:

1.Object push(Object o);

to insert an object into the stack.

2.Object pop();

 to remove an return top of the stack.

3.Object peek();

to return top of the stack without removal.

4.boolean empty();

returns true if the stack is empty

5.int search(Object 0);

 returns offset if the element is available otherwise returns -1.

48
import java.util.Stack;

public class stackdemo {


public static void main(String[] args) {
Stack s=new Stack();
s.push("A");
s.push("B");
s.push("C");
System.out.println(s);
System.out.println(s.search("A"));
System.out.println(s.search("Z"));
}

}
Output:
[A, B, C]
3
-1

Three cursors of java:

If we want to get objects one by one from the collections then we should go for
cursors.

There are 3 types of cursors in java:

 Enumeration
 Iterator
 ListIterator

Enumeration:

 We can use Enumeration to get objects one by one from Legacy Collection
object.
 We can create Enumeration object by using elements method of vector
class.

public Enumeration e = v.elements();

 Methods:
1>public boolean hasMoreElements();
2>public Object nextElement();

Limitation of Enumeration:

 We can apply enumeration concept only for legacy classes and it is not a
universal crosser.

49
 By using enumeration we can get only read access and we cant
performance remove operation to over come above limitation we should go
for iterator.
package basic_problems;

import java.util.Enumeration;
import java.util.Vector;

public class enumDemo {


public static void main(String[] args) {
Vector v =new Vector();
for(int i=0;i<=10;i++) {
v.addElement(i);
}
System.out.println(v);
Enumeration e=v.elements();
while (e.hasMoreElements()) {
Integer i= (Integer) e.nextElement();
if(i%2 == 0) {
System.out.println(i);

}
}
System.out.println(v);

}
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
0
2
4
6
8
10
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Iterator:

We can apply iterator concept for any collection object and hence it is universal
crosser.

By using iterator we can perform both read and remove operation ,

We can iterate object by using iterator method of collection interface.

public Iterator iterator();

Example:

 Iterator itr=c.Iterator(); c any collection

Methods of Iterator:

 Public boolean hasNext();

50
 Public object next();
 Public void remove();

package basic_problems;

import java.util.ArrayList;
import java.util.Iterator;

public class iteratordemo {


public static void main(String[] args) {
ArrayList l=new ArrayList();
for(int i=0;i<=10;i++) {
l.add(i);
}
System.out.println(l);
Iterator itr =l.iterator();
while(itr.hasNext()) {
Integer i=(Integer)itr.next();
if(i %2==0) {
System.out.println(i);
}else {
itr.remove();
}
}
System.out.println(l);
}
}
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
0
2
4
6
8
10
[0, 2, 4, 6, 8, 10]

Limitation of Iterator:

 By using Enumeration & Iterator , we can always move only in Forword


direction and we cannot move backwards.
 These are single direction cursors but not bi-directional cursors.
 By using Iterator , we can perform only read and remove operations and
we cannot perform replacement and addition of new objects to overcome
above limitation we should go for listIterator cursor.

ListIterator:-

By using, ListIterator we can move either in forward direction or in backward


direction and hence it is bi-directional cursors.

51
By using ListIterator, we can perform replacement and addition of new objects.

We can create ListIterator, by using ListIterator() method of List Interface.

public ListIterator listiterator();

e.g., ListIterator ltr = l.listiterator();

ListIterator is the child Interface of Iterator and hence all method which are
present in Iterator. By default, available to the ListIterator.

 ListIterator defines the following 9 methods: -

52
package basic_problems;

import java.util.LinkedList;
import java.util.ListIterator;

public class ListIteratordemo {


public static void main(String[] args) {
LinkedList l=new LinkedList();
l.add("balakrishna");
l.add("venki");
l.add("chiru");
l.add("nag");
System.out.println(l); //[balakrishna, venki, chiru, nag]
ListIterator ltr=l.listIterator();
while(ltr.hasNext()) {
String s=(String)ltr.next();
if(s.equals("venki")) {
ltr.remove();

}
else if(s.equals("Nag")) {
ltr.add("Utpal");
}
else if(s.equals("chiru")) {
ltr.set("predep");
}

53
}
System.out.println(l);//[balakrishna, predep, nag]
}
}
The most powerful cursors is list iterator but its limitation is it appliable only
for list object.

Comparison table for the cursors.

Property Enumeration iterator Listiterator

Where we Only for legacy For any collection Only for list object.
can apply classes. object.
moment Single direction Single direction Bi-direction
(only forward (only forward
direction) direction)
Is it legacy Yes 1.0 v No 1.2 v No 1.2v
Allowed Only read Read/remove Read/remove/replace
operation
How we can By using elements() By using iterator() By using list iterator
get of vector class Of collection(i) of list()
methods hasMoreElements() hasNext() All 9 methods
nextElement() next()
remove()
import java.util.Enumeration;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Vector;

public class getclassdemoo {


public static void main(String[] args) {
Vector<Object> v=new Vector<Object>();
Enumeration<Object> e=v.elements();
Iterator <Object>itr=v.iterator();
ListIterator<Object> ltr=v.listIterator();
System.out.println(e.getClass().getName());
System.out.println(itr.getClass().getName());
System.out.println(ltr.getClass().getName());
}
}
Output:
java.util.Vector$1
java.util.Vector$Itr
java.util.Vector$ListItr

54
Set:
Set

HashSet 1.2 v SortedSet(i)1.2

linkedHashSet 1.4v NavigableSet(i)1.6

treeSet

> Ste is the child interface of collection

> if we want to represent a group of individual object as a single entity where


duplicate are not allowed and insertion order not preserved.

>set interface doesn’t contain any new method and we have to use only collection
interface methods.

HashSet:

The underlying Data Structure is HashTable.

 Duplicate objects are not allowed.


 Insertion order is not preserved.
 It is based on Hash Code of the object.
 Null insertion is possible (only once)
 Heterogenies object are allowed.
 Implementation Serializable and cloneable but not random-access
interface.
 HashSet is the best choice if our frequent operation is searching
operation.

Note: in HashSet duplicate are not allowed if we are trying insert duplicate
then we will not get any compile or runtime error and add method simple return
false.
import java.util.HashSet;

public class hashSetdemo {


public static void main(String[] args) {
HashSet <Object>h=new HashSet<Object>();
h.add("Nithish");
h.add("Kumar");
h.add(null);
h.add(null);
System.out.println(h.add("Nithish"));
System.out.println(h);
}

55
}
Output:
false
[null, Kumar, Nithish]
Constructor:

1>HashSet h=new HashSet();

create an empty HashSet object with default initial capacity 16 and default
fill ratio 0.75.

2>HashSet h=new HashSet(int initalCapacity);

creates an empty HashSet object with specified initial capacity and default
fill ratio 0.75.

3>HashSet h=new HashSet(int intialcapacity ,float fill ratio);

4>HashSet h=new HashSet(collection c);

create an equivalent HashSet for the given collection this constructor meant
for interconversion between collection.

Fill ratio or load factor :

After filling how much ratio a new hash set object will be created this ratio is
called fill ratio or load factor.

Fill ratio 0.75 means after filling 75% ratio a new HashSet object will be
created.
package basic_problems;

import java.util.HashSet;

public class hashsetdemoo {


public static void main(String[] args) {
HashSet<Object> h= new HashSet<Object>();
h.add("B");
h.add("C");
h.add("D");
h.add("Z");
h.add(null);
h.add(10);
h.add(null);
System.out.println(h.add("Z"));
System.out.println(h);

}
Output:
false
[null, B, C, D,: Z, 10] output depends on hash table

56
LinkedHashSet:

It is the child class of the HashSet.

It is exactly same as HashSet Including constructor and method except the


following difference.

HashSet LinkedHashSet
The underlying Data Structure is Underlying Data Structure is
HashTable. Combination of Linkedlist and
HashTable.
Insertion order not preserved Insertion order preserved
Introduction in 1.2 version Introduced in 1.4 version

import java.util.LinkedHashSet;

public class linkedhashsetdemo {


public static void main(String[] args) {
LinkedHashSet<Object> h= new LinkedHashSet<Object>();
h.add("B");
h.add("C");
h.add("D");
h.add("Z");
h.add(null);
h.add(10);
h.add(null);
System.out.println(h.add("Z"));
System.out.println(h);
}

}
Output:
false
[B, C, D, Z, null, 10]
Note: in general we can used LinkedHashSet to develop cache based application
whenever duplicate are not allowed insertion order not preserved.

SortedSet:

 Sorted set is the child interface of set.


 If we want to represent a group of Individual object according to some
sorting order without duplicate then we should go for sorted set.

SortedSet interface defines the following specific methods.

1>Object first() returns first element of the SortedSet.

2>object last() returns last element of the SortedSet.

.w

57
3> SortedSet headset(object obj) ;

returns sorted set whose elements are < object.

4>SortedSet tail Set(object obj);

returns SortedSet where elements are >=object

5>Sorted subset(object obj1, object obj2);

 Returns SortedSet whose elements are >=object 1 and < object2

Comparator Comparator()

->returns comparator object that describe underlying shorting techniques if we


are default natural shorting order then we will get null.

NOTE:- that default natural shorting order for numbers ascending order for
string alphabetical order.
import java.util.SortedSet;
import java.util.TreeSet;

public class sortedsetdemo {


public static void main(String[] args) {
SortedSet<Object> ss=new TreeSet<>();
ss.add(100);
ss.add(101);
ss.add(104);
ss.add(106);
ss.add(115);
ss.add(120);
System.out.println(ss);
System.out.println(ss.first());
System.out.println(ss.last());
System.out.println(ss.headSet(106));
System.out.println(ss.tailSet(106));
System.out.println(ss.subSet(101, 115));
System.out.println(ss.comparator());
}

Output:
100
120
[100, 101, 104]
[106, 115, 120]
[101, 104, 106]
null

58
TreeSet (implementation class):

 The underlying Data Structure is Balanced tree.


 Duplicate object are not allowed.
 Insertion order not preserved.
 Heterogenous object are not allowed other wise we will get runtime
exception saying class cast exception.
 Null insertion possible (only once).
 Tree Set implement serlilzabale and cloneable not random access.
 All objects insertion based on some shorting order it may be default
natural shorting order or customise shorting order.

Constructor:

1>TreeSet t=new TreeSet();

 creates an empty TreeSet object where the element will inserted according
to default natural shorting order.

2>TreeSet t=new TreeSet(comparator c);

creates an empty TreeSet element will be insert according to customized


order specified by comparator object.

3>TreeSet t=new TreeSet(collection c);

4>TreeSet t= new TreeSet(SortedSet c);


import java.util.TreeSet;

public class treesetdemoo {


public static void main(String[] args) {
TreeSet<Object> ts=new TreeSet<>();
ts.add("A");
ts.add("a");
ts.add("B");
ts.add("Z");
ts.add("L");
// ts.add(new Integer(10));
// ts.add(null);
System.out.println(ts);
}

}
Output:
[A, B, L, Z, a]

59
Null acceptance :

For non-empty tree Set if we are trying to insert null then we will get null
pointer exception.

For empty tree set as the first element null is allowed but after inserting that
null if we are trying to insert any other we will get runtime exception saying null
pointer exception.

Note: until 1.6 version null is allowed as the first element to the empty tree set
.but 1.7 v onwards null is not allowed even as the first element that is null such

Type of storing not applicable for tree set from 1.7 version onwards.

If we are depending on default natural shorting order compulsory the object


should be homogenous and comparable otherwise we will get runtime exception

Saying class cast exception.

An object is said to be comparable if and only if corresponding class implements

Comparable interface.

String class and all wrapper classes already implement comparable interface but
StringBuffer class doesn’t implements comparable interface hence we got class
cast exception in the above example.

\\Vvip//

You’re converting StringBuffer to String in comparator and string class


implement comparable interface and also has a note science from JDK 11
StringBuffer and StringBuilder also implements comparable.

Comparable(I):

It is present in java.lang package and it contains only one method.

compareTo();

Syntax:

Public int compareTo(object obj);

Obj1 .compareTo(obj2); ->returns -ve if object 1 has to come before obj2

->return +ve if object 1 has to come after object 2

->return 0 if obj1 and obj2 are equal


public class treeesetff {

60
public static void main(String[] args) {
System.out.println("A".compareTo("Z"));
System.out.println("Z".compareTo("K"));
System.out.println("A".compareTo("A"));
System.out.println("A".compareTo(null)); nuupointer execptio
}

}
Output:
-25
15
0

If we are depending on default natural shorting order then while adding object
into the tree ,tree set JVM will called comparTo().

Obj1.comparTo(obj 2);

The object
The object which which already
is to be inserted inserted

public class treeeeedemo {


public static void main(String[] args) {
TreeSet<Object> t=new TreeSet<>();
t.add("K");
t.add("A");
t.add("Z");
t.add("A");
System.out.println(t);
}

}
Output:
[A k Z]
If default natural shorting order not available or if we are not satisfied the we
can go for customized sorting by using comparator.

Comparable: meant for default natural sorting order

Where as

Comparator: meant for customized sorting order

61
Comparator: comparator present in java util package and it defines two method.

 Compare();
 equals();

1>public int compare(object obj1, object obj2);

 returns -ve if and only id obj1 has to come before obj2.


 Return +ve if and only if obj1 has to come after obj 2.
 Return 0 if obj 1 and obj 2

Whenever we implementing comparator interface compulsory we should provide


implementation only for compare method we are not required to prove
implementation for equal methods because it is already available to our class
from object class through inheritance.

Write a program to insert integer object into the tree set where the
shorting order is descending order.
package basic_problems;

import java.util.Comparator;
import java.util.TreeSet;

public class treedemoooo {


public static void main(String[] args) {
TreeSet<Object> t=new TreeSet<>(new MyComparator());
t.add(10);
t.add(0);
t.add(15);
t.add(15);
t.add(5);
t.add(20);
t.add(20);
System.out.println(t);
}

}
class MyComparator implements Comparator{

@Override
public int compare(Object o1, Object o2) {
Integer i1=(Integer)o1;
Integer i2=(Integer)o2;
if(i1 < i2) {
return +1;
}else if(i1>i2) {
return-1;
}else {
return 0;

62
}

}
Output:
[20, 15, 10, 5, 0]

 At line 1,if we are not passing comparator object then internally JVM will
call compareTo() which is meant for natural sorting order .in case the
output is [0,5,10,15,20]
 At line 1,if we are passing comparator object then JVM will call compare()
which meant for customized sorting order in this case output is
descending order. [20,15,10,5,0]
 Various possible implementations of compare method:
1>return i1.compareTo(i2);
->returns default natural sorting order which is ascending order.
2>return -i1.compareTo(i2);
->return the elements in descending order.
3>return -i2.compareTo(i1);
->returns default natural sorting order which is ascending order.
4>return +1;
->return elements similar to insertion order

63
5>return -1;
->return reverse of insertion order.
6>return 0;
->only first element will be inserted and remaining will be considered as
duplicate

Write a program to insert String object into treeSet where all elements
should be inserted according to reverse of alphabetical order.
package basic_problems;

import java.util.Comparator;
import java.util.TreeSet;

public class trrredemo {


public static void main(String[] args) {
TreeSet <String>t=new TreeSet<>();
t.add("nithish");
t.add("vamshi");
t.add("rajesh");
t.add("balakrishna");
System.out.println(t);
}
}
class mycoum implements Comparator{

@Override
public int compare(Object o1, Object o2) {
String s1=(String)o1;
String s2=(String)o2;
return s2.compareTo(s1);
// return -s1.compareTo(s2);
}

}
Output:
[balakrishna, nithish, rajesh, vamshi]
Write a program to insert StringBuffer objects into the treeSet where
order is alphabetical order insert A,Z,K,L.
package basic_problems;

import java.util.Comparator;
import java.util.TreeSet;

public class treebuffer {


public static void main(String[] args) {
TreeSet <Object>t=new TreeSet<>();
t.add(new StringBuffer("A"));
t.add(new StringBuffer("Z"));
t.add(new StringBuffer("K"));
t.add(new StringBuffer("L"));
System.out.println(t);
}

}
class mycoume implements Comparator{

64
@Override
public int compare(Object o1, Object o2) {
String s1=o1.toString();
String s2=o2.toString();
return s1.compareTo(s2);
}

}
Output:
A, K, L, Z]
Note:

->if we are depending on default natural sorting order compulsory object, should
we homogenous and comparable otherwise we will get runtime exception saying
ClassCastException.

->if we are defining our own sorting order by using comparator then object need
not be comparable and homogeneous i.e ,we can add heterogeneous non-
comparable objects also.

Write a program to insert String and StringBuffer object into TreeSet where
sorting order is increasing length order. If two objects having same length then
consider their alphabetical order.

“ABC” StringBuffer, “AA” StringBuffer, “XX”, “ABCD”, “A”


package basic_problems;

import java.util.Comparator;
import java.util.TreeSet;

public class treedemoo {


public static void main(String[] args) {
TreeSet<Object> t=new TreeSet<>(new MyComupo());
t.add(new StringBuffer("ABC"));
t.add(new StringBuffer("AA"));
t.add("XX");
t.add("ABCD");
t.add("A");
System.out.println(t);
}

}
class MyComupo implements Comparator{

@Override
public int compare(Object o1, Object o2) {
String s1=o1.toString();
String s2=o2.toString();
if(s1.length() < s2.length()) {
return -1;
} else if(s1.length() > s2.length()) {
return +1;
} else {
return s1.compareTo(s2);

65
}

}
[A, AA, XX, ABC, ABCD]
Comparable vs Comparator:

 For pre-defined comparable classes default natural sorting order is


already available. If we are not satisfied with default natural sorting
order then we can define our own sorting order by using Comparator.
 For pre-defined non-comparable classes like (StringBuffer) default
natural sorting order is not already available .we can define our own
sorting comparator.
 For our own classes like Employee the person who writing the class is
responsible to define default natural sorting order by implementing
comparable interface.
 The person who is using our class ,if he is not satisfied with default
natural sorting order then he can define his own sorting by using
comparator.

package basic_problems;

import java.util.Comparator;
import java.util.TreeSet;

class Employee implements Comparable{


String name;
int eid;
public Employee(String name,int eid) {
this.name=name;
this.eid=eid;
}

66
@Override
public String toString() {
return name + "--" + eid ;
}
@Override
public int compareTo(Object o) {
int eid1 = this.eid;
Employee e = (Employee) o;
int eid2 = e.eid;
if(eid1 < eid2) {
return -1;
} else if(eid1 > eid2) {
return +1;
} else {
return 0;
}

}
}
public class demo22 {
public static void main(String[] args) {
Employee e1 = new Employee("nag", 100);
Employee e2 = new Employee("balaiah", 200);
Employee e3 = new Employee("chiru", 50);
Employee e4 = new Employee("venki", 150);
Employee e5 = new Employee("nag", 150);
TreeSet <Object>t=new TreeSet<>();
t.add(e1);
t.add(e2);
t.add(e3);
t.add(e4);
t.add(e5);
System.out.println(t);
TreeSet<Object> t1=new TreeSet<>( new mycomparator());
t1.add(e1);
t1.add(e2);
t1.add(e3);
t1.add(e4);
t1.add(e5);
System.out.println(t1);
}

}
class mycomparator implements Comparator{

@Override
public int compare(Object o1, Object o2) {
Employee e1=(Employee)o1;
Employee e2=(Employee)o2;
String s1=e1.name;
String s2=e2.name;
return s1.compareTo(s2);

}
}
Output:
[chiru--50, nag--100, venki--150, balaiah--200]
[balaiah--200, chiru--50, nag--100, venki--150]

67
Difference between Comparable Nd Comparator

Comparable Comparator
It is meant for default natural sorting It is meant for customized sorting
order order
Preset in java.lang package Present in java.util package
It defines only one method It defines two methods
compareTo() Compare()
equals()
String and wrapper classes implements The only implemented classes of
comparable class comparator are:
Collator
RuleBasedCollator
Comparison of Set implemented classes

Property HashSet LinkedHashSet TreeSet


Underlying HashTable Combination of BalancedTree
Data Structure linkedlist &
HashTable
Duplicate Objects Not allowed Not allowed Not allowed
Insertion order Not preserved preserved Not preserved
Sorting order Not applicable Not applicable Applicable
Heterogeneous Allowed Allowed Not allowed
Null acceptance allowed allowed For empty treeSet
as first element null
is allowed .
Note ;-rule is
applicable until 1.6
form 1.7 onwards null
is not allowed even
as the first element.

Map:

 Map is not a child interface of collection.


 If we want to represent group of individual objects as key-value pairs
then we should go for map.
 Both key and value are object only.
 Duplicate key-value pair is called entry.

68
Map interface methods:

1>object put(Object key ,object value);

To add one key-value pair to the map , if the key is already present then old
value will be replaced with new value and returns old value.

2>void putAll(Map m);

3>Object get(Object key);// return the value associated with specified key.

4>object remove(object key );// remove the entry associated with specified
key.

5>boolean containsKey(Object Key);

6>boolean containsValue(object value);

7>boolean isEmpty();

8>int size();

9void clear();

69
Entry(i);

1>Map is a group of key-value pairs and each key-value pairs is called an entry.

2>Hence, Map is considered as collection of Entry objects without existing map


object there is no chance of existing entry object hence entry(i) is defined
inside Map(i).

HashMap:-

 Underlying data structure is HashTable.


 Insertion order is not preserved and it is based on hash code of keys.
 Duplicate key are not allowed but values can be duplicated.
 Heterogeneous object are allowed for both keys and values.
 Null is allowed for key(only once).
 Null is allowed for values any number of times.
 HashMap implements serializable and cloneable interface but not random
access.
 HashMap is the best choice if our frequent operation is searching
operation.

Constructor of HashMap:-

 HashMap m=new HashMap();


Creates an empty HashMap object with default capacity 16 and default
fill ratio 0.75
 HashMap m= new HashMap (int initialCapacity);
Creates an empty HashMap object with specified initial capacity and
default fil ratio 0.75
 HashMap m=new HashMap(int initialCapacity, float fillratio);
 HashMap m=new HashMap(map m);

70
package basic_problems;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class hashmapdemo {


public static void main(String[] args) {
HashMap m=new HashMap();
m.put("Chiranjeevi", 700);
m.put("balaiah", 800);
m.put("venkatesh", 200);
m.put("nagarjun", 500);
System.out.println(m);//{nagarjun=500, balaya=800,
venkatesh=200, Chiranjeevi=700}
System.out.println(m.put("Chiranjeevi", 1000));//return old
value 700
System.out.println(m);//{nagarjun=500, balaya=800,
venkatesh=200, Chiranjeevi=1000}
Set s=m.keySet();
System.out.println(s);//[nagarjun, balaiah, venkatesh,
Chiranjeevi]
Collection c=m.values();
System.out.println(c);//[500, 800, 200, 1000]
Set s1=m.entrySet();
System.out.println(s1);//[nagarjun=500, balaiah=800,
venkatesh=200, Chiranjeevi=1000]
Iterator itr=s1.iterator();
while(itr.hasNext()) {
Map.Entry m1=(Entry)itr.next();
System.out.println(m1.getKey()+" "+m1.getValue());
/* nagarjun 500
balaiah 800
venkatesh 200
Chiranjeevi 1000*/
if (m1.getKey().equals("Nagarjuna")) {
m1.setValue(1000);
}
}
System.out.println(m);//{nagarjun=500, balaiah=800,
venkatesh=200, Chiranjeevi=1000}
}

}
Output:
{nagarjun=500, balaiah=800, venkatesh=200, Chiranjeevi=700}
700
{nagarjun=500, balaiah=800, venkatesh=200, Chiranjeevi=1000}
[nagarjun, balaiah, venkatesh, Chiranjeevi]
[500, 800, 200, 1000]
[nagarjun=500, balaiah=800, venkatesh=200, Chiranjeevi=1000]
nagarjun 500
balaiah 800
venkatesh 200
Chiranjeevi 1000
{nagarjun=500, balaiah=800, venkatesh=200, Chiranjeevi=1000}

71
Difference between HashMap and HashTable:

HashMap HashTable
Every method present in HashMap are Every method present in HashTable
not synchronized. are synchronized.
At a time ,multiple threads are allowed At a time only one thread is allowed to
to operate on HashMap and hence it is operate on HashTable and hence it is
not thread safe. thread safe.
Relatively performance is high because Relatively performance is low because
threes are not required to wait to threads are required to wait to
operate on HashMap object operate on HashTable object.
Null is allowed for both key and value. Null is not allowed for keys and values
otherwise we will get
NullPointerException.
Introduced in 1.2 v and it is not legacy Introduced in 1.0 and it is legacy
In the above ,HashMap program if we replace HashMap with LinkedHashMap
the output will be different
package pack;

import java.util.*;
import java.util.Map.Entry;

public class Demo18 {


public static void main(String[] args) {
LinkedHashMap m = new LinkedHashMap();
m.put("Chiranjeevi", 700);
m.put("balaiah", 800);
m.put("Venkatesh", 200);
m.put("Nagarjuna", 500);
System.out.println(m); // {Chiranjeevi=700, balaiah=800,
Venkatesh=200, Nagarjuna=500}
System.out.println(m.put("Chiranjeevi", 1000)); //
700
System.out.println(m);
Set s = m.keySet(); // {Chiranjeevi=1000,
balaiah=800, Venkatesh=200, Nagarjuna=500}
System.out.println(s); // [Chiranjeevi, balaiah,
Venkatesh, Nagarjuna]
Collection c = m.values();
System.out.println(c); // [1000, 800, 200, 500]
Set s1 = m.entrySet();
System.out.println(s1); // [Chiranjeevi=1000,
balaiah=800, Venkatesh=200, Nagarjuna=500]

Iterator itr = s1.iterator();


while (itr.hasNext()) {
72
Map.Entry m1 = (Entry) itr.next();
System.out.println(m1.getKey() + " " +
m1.getValue());
/*
Chiranjeevi 1000
balaiah 800
Venkatesh 200
Nagarjuna 500
*/
if(m1.getKey().equals("Nagarjuna")) {
m1.setValue(10000);
}
}
System.out.println(m); // {Chiranjeevi=1000,
balaiah=800, Venkatesh=200, Nagarjuna=10000}
}
}
Output:
{Chiranjeevi=700, balaiah=800, Venkatesh=200, Nagarjuna=500}
700
{Chiranjeevi=1000, balaiah=800, Venkatesh=200, Nagarjuna=500}
[Chiranjeevi, balaiah, Venkatesh, Nagarjuna]
[1000, 800, 200, 500]
[Chiranjeevi=1000, balaiah=800, Venkatesh=200, Nagarjuna=500]
Chiranjeevi 1000
balaiah 800
Venkatesh 200
Nagarjuna 500
{Chiranjeevi=1000, balaiah=800, Venkatesh=200,
Nagarjuna=10000}
Note:-

 LinkedHashSet and LinkedHashMap are commonly used for developing


Cache based application.
 Difference between ‘ == ’ operator and .equals()
 In general,== operator is meant for reference comparison (address
comparison) where .equals is meant for contact compassion.

73
IdentityHashMap:-

 It is exactly same as HashMap including methods and constructor except


the following differences.
 In the case of normal HashMap ,JVM will use normal .equals() method to
identify duplicate keys which is meant for content comparison
 But in the case of identityHashMap JVM will used == operator to identify
duplicate key which is meant for address comparison.

package basic_problems;

import java.util.HashMap;
import java.util.IdentityHashMap;

public class HashMapdemooo {


public static void main(String[] args) {
System.out.println("===========in the case of Hash map=====");
HashMap m=new HashMap();
Integer i1=new Integer(10);
Integer i2=new Integer(10);
m.put(i1, "pawan");
m.put(i2, "Kalyan");
System.out.println(m);
System.out.println();
System.out.println();
System.out.println(“============in the caser of identiyhashmap======
”);
IdentityHashMap im=new IdentityHashMap();
im.put(i1, "Pawan");
im.put(i2, "Kalyan");
System.out.println(im);
}
}
Output:
===========in the case of Hash map=====
{10=Kalyan}

============in the caser of identiyhashmap======


{10=Pawan, 10=Kalyan}

 In general, == operate is meant for reference comparison


 .equals is meant for contact comparison
 In the case of normal HashMap JVM will use .equals() to identify
duplicate key which is meant for contact comparison
 In identity HashMap JVM will use == operator which is meant for
reference comparison.

74
 I1 and i2 are duplicate key because i1.equals(i2) true.
 If we replace HashMap with identityHashMap then i1 and i2 are not
duplicate keys in that case it returns false.
 In the case output is
 ===========in the case of Hash map=====
 {10=Kalyan}


 ============in the caser of identiyhashmap======
 {10=Pawan, 10=Kalyan}

WeakHashMap:-

It is exactly same as HashMap except the following differences:

 In the case of HashMap even though object does not have any reference
variable it is not eligible for garbage collection(GC).

If it is associated with HashMap i.e.. , HashMap if object doesn’t contain


collector But ,in the case of WeakHashMap if Object doesn’t contain any
references ,it is eligible for GC ,even though an object is associated with
WeakHashMap i.e.. GC dominates WeakHashMap.
package basic_problems;

import java.util.HashMap;

class temp1{
public String toString() {
return "Temp1";

}
public void finalize() {
System.out.println("Finalize method called");
}

75
public class demo55 {
public static void main(String[] args) throws InterruptedException {
HashMap m=new HashMap();
temp1 t=new temp1();
m.put(t, "utpal");
System.out.println(m);
t=null;
System.gc();
Thread.sleep(5000);
System.out.println(m);
}

}
Output:
{Temp1=utpal}
{Temp1=utpal}
In the above example ,temp object is not available for GC because it is
associated with HashMap.

In the above program if we replace HashMap with WeakHashMap temp object is


eligible for GC.
package basic_problems;

import java.util.WeakHashMap;

class temp1{
public String toString() {
return "Temp1";

}
public void finalize() {
System.out.println("Finalize method called");
}

public class demo55 {


public static void main(String[] args) throws InterruptedException {
WeakHashMap m=new WeakHashMap();
temp1 t=new temp1();
m.put(t, "utpal");
System.out.println(m);
t=null;
System.gc();
Thread.sleep(5000);
System.out.println(m);
}

}
Output:
{Temp1=utpal}
Finalize method called
{}

76
SortedMap:-

 It is the child interface of map.


 If we want to represent a group of objects as key-value pairs according
to some sorting order of keys then we should go for SortedMap.
 Sorting is based on the keys but not based on the values.

Methods of SortedMap:-

 Object firstKey();
 Object LastKey();
 SortedMap headMap (Object Key);
 SortedMap tailMap(Object Key);
 SortedMap submap(Object key1,object key2);
 Comparator comparator();

TreeMap:-

 The underlaying Data Structure is ‘Red Black Tree’.


 Insertion order id not preserved and it is based on some sorting order of
keys.
 Duplicate keys are not allowed but values can be duplicated.
 If we are depending on default natural shorting order then keys should
be homogenous and comparable otherwise we will get runtime exception
saying ClassCastException.
 If we are defining own sorting by comparator then keys need not be
homogeneous and comparable we can take heterogeneous non comparable
object also

77
 Whether we are depending on default natural sorting order or customized
sorting order, there are restrictions for values we can take
heterogeneous non-comparable objects.

Null acceptance in TreeMap:-

 For a non-empty TreeMap ,if we are trying to insert an entry with null key
we will get runtime exception saying NullPointerException.
 For empty TreeMap ,as the first entry with null key but after inserting
that key and if we are trying to insert any another Entry saying
NullPointerException.

Constructors of TreeMap:-

1>TreeMap t=new TreeMap();

For default natural sorting order.

2>TreeMap t=new TreeMap(Comparator c);

For customized sorting order.

3>TreeMap t=new TreeMap(SortedMap m);

4>TreeMap t= new TreeMap(Map m);

Demo program for default natural shorting order for TreeMap.


import java.util.TreeMap;

public class treedemodefualt {


public static void main(String[] args) {
TreeMap tm=new TreeMap();
tm.put(505, "nithish kumar");
tm.put(506,"ravan brother");
tm.put(230, "kumar babu");
tm.put(104, "g samab siva rao");
System.out.println(tm);
}
}
Output:
{104=g samab siva rao, 230=kumar babu, 505=nithish kumar,
506=ravan brother}

78
Demo program for customize shorting order for TreeMap.
import java.util.Comparator;
import java.util.TreeMap;

public class treedemodefualt {


public static void main(String[] args) {
TreeMap tm=new TreeMap();
tm.put(505, "nithish kumar");
tm.put(506,"ravan brother");
tm.put(230, "kumar babu");
tm.put(104, "g samab siva rao");
System.out.println(tm);
}
}
class bro implements Comparator{

@Override
public int compare(Object o1, Object o2) {
String s1=o1.toString();
String s2=o2.toString();
return s2.compareTo(s1);
}

}
Output:
{104=g samab siva rao, 230=kumar babu, 505=nithish kumar, 506=ravan
brother}

HashTable:

 The underlying Data structure for HashTable is HashTable.


 Insertion order is not preserved and it is based on hashcode of keys.
 Duplicate keys are not allowed but values can be duplicated.
 Heterogenies object allowed for both keys and value.
 Null is not allowed for both keys and values otherwise we will get runtime
exception saying ‘null pointer exception’.
 It implements serializable and cloneable interface but not random access.
 Every method present in HashTable is synchronised and hence HashTable
object is thread safe.
 HashTable is best choice if our frequent operation is retrieval operation
or search operation.
 It is worst for insertion and deletion.

Constructors :

1>HashTable h=new HashTable ();

Creates an empty HashTable object with default initial capacity 11 and fill ratio
75%.

79
2>HashTable h=new HashTable(int initial capacity);

Creates an empty HashTable object with initial capacity .

3>HashTable h=new HashTable(int initial capacity ,float fill ratio);

4>HashTable h=new HashTable(Map m);

Properties:

In our program if anything change frequently like(username, password ,email_id,


mobile number etc) are not required to hardcode. In java program because if
there is any change to reflected that changes recompilation , rebuild , redeploy
application are required even some times server restart required which creates
big business impact to the client.

We can overcome this problem by using properties file such type of variable
things we have configure in the properties file from that properties file we
have to read into java program we can use those properties.

The main advantage of this approach is if there is a change in a properties file


to reflect that change just redeployment is enough which will not create any
business effected to the client we can use java properties object to hold
properties which are coming from properties file in normal Map(like HashMap,
HashTable TreeMap)key and value can be any type but in the case of properties
key and value should be String. [put(“1000”,”Nithish”]

Constructor:

Properties p= new Properties();

Methods:

1>String SetProperties (String Pname, String Pvalue);

To set a new propriety if the specified property already available then old value
will represent with new and return old value.

2>String getproperty(String Pname);

To get value associated with the specified property not available then this
method will return null.

3>enumeration property Names();

>return all property names present in object.

80
4>void load(inputStream is);

> To load properties from properties file into java properties object.

5>void store (output Stream as ,String Comment);

>to store properties from java properties object properties file.

Load()

Properties file Java properties


object

Store()

import java.util.Properties;

public class propertiesDemo {


public static void main(String[] args) {
Properties p =new Properties();
fileInputStrem fis=new fileInputStrem("abc.properties");
p.load(fis);
System.out.println(p);//{pn=pv-----}
String s=p.getProperty("Utpal");
System.out.println(s);
p.setProperty("manas", "88888");
FileOutpuStrem fos=new FileOutPutStrem("abc.properties";)
p.store(fos,"updated by ytpal for excelr demo class);

import java.util.Properties;

public class demooo {


public static void main(String[] args) {
Properties p=new Properties();
FileInputStrem fis=new FileInputStrem("db.properties");
p.load(fis);
String url1=p.getProperty("url");
String user=p.getProperty("user");
String pwd =p.getProperty("pwd");
Connection con=DriverManger.getConnection(url,user,pwd);

81
Queue:

 1.5 version enhancement queue interface.


 It is the child interface of collection.
 If we want represent a group individual objects prior to processing then
we should go for queue.

Example: before sending SMS all number to store some date structure in which
order we have added numbers in the same order only SMS should be delivered
from this FIFO requirement queue is best choice.

Collection

List queue 1.5 version

set Blocking Queue

priority Queue Priority blocking Q

linked Blocked Q

 Usually Queue follows FIFO based on our requirement we can implement


our own priority order also priority queue,
 From 1.5v onwards linked list class also implements queue interface.
 Linkedlist based on implements of queue always follows FIFO .

Method:

1>boolean offer(object o);

to add an object into the Queue.

2>Object peek()

to return head element of the queue if queue is empty then this method
returns null.

3>object element();

to return head element of the queue if queue is empty this method returns
runtime exception saying No Such Element Exception.

82
4>object poll();

to remove and return head element of the queue , if queue is empty this
methods returns null.

5>object remove();

to remove and return head element of the queue if queue is empty this
method raise exception nosuchelement exception.

Priority Queue:

 If we want represent group individual objects prior to processing


according to some priority then we should go for priority queue.
 The priority can be either default natural sorting order or customized
sorting order defined by comparator.
 Insertion order is not preserved and it is based on priority.
 Duplicate objects are not allowed.
 If we are depending on default natural sorting order compulsory objects
should be homogenous and comparable otherwise we get re saying Class
Cast Exception.
 If we are defining our own sorting by comparator then object need not be
homogenous and comparable.
 Null is not allowed even as first element also.

Constructor:

1> priorityQueue q=new priorityQueue();

creates empty priority Queue object default capacity 11 and all object will
be inserted according to default natural sorting order.

2> priorityQueue q=new priorityQueue(int initialCapacity);

3>priorityQueue q=new priorityQueue (int initialCapacity comparator c);

4> priorityQueue q=new priorityQueue(SortedSet S);

5> priorityQueue q=new priorityQueue(Collection c);

83
Demo for default natural shorting order
package basic_problems;

import java.util.PriorityQueue;

public class proprityqueuedemo {


public static void main(String[] args) {
PriorityQueue q=new PriorityQueue();
System.out.println(q.peek());//null
// System.out.println(q.element()); re no suchelement exception
for(int i=0;i<=10;i++) {
q.offer(i);

}
System.out.println(q);//[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
System.out.println(q.poll());//0
System.out.println(q);//[1, 3, 2, 7, 4, 5, 6, 10, 8, 9]
// note some platform will not provide proper support for
// thread priorites and priority queue.

}
Demo for customized shorting order.
package basic_problems;

import java.util.Comparator;
import java.util.PriorityQueue;

public class customizedemo {


public static void main(String[] args) {
PriorityQueue q=new PriorityQueue(15,new mycompaaa());
q.offer("A");
q.offer("Z");
q.offer("L");
q.offer("B");
System.out.println(q);//[A, B, L, Z]
}

}
class mycompaaa implements Comparator{

@Override
public int compare(Object o1, Object o2) {
String s1=(String)o1;
String s2=(String)o2 ;
// return s2.compareTo(s1);//[Z, B, L, A]
return s1.compareTo(s2);//[A, B, L, Z]
}

84
1.6 Enhancement in collection framework:

> as a part of 1.6 v the following two concept introduced in 1.6 v

 navigable set
 navigable map

navigable set:

it is the child interface of SortedSet and it defines several methods for


navigation purpose.

Methods:

1>Floor(e);

it returns highest element which is <=e

2>lower(e);

it returns highest element which is <e

3>celing(e);

it returns lowest element which is >=

4>higher(e);

it returns lowest element which is >e

5>pollfirst();

remove and return first element

6>poolLast();

remove and return last element

7> descendingSet();

it returns navigable set-in revers order


package basic_problems;

import java.util.TreeSet;

public class navigbalsetdemo {


public static void main(String[] args) {
TreeSet <Integer> t=new TreeSet<>();
t.add(1000);
t.add(2000);
t.add(3000);
t.add(4000);
t.add(5000);

85
System.out.println(t);//[1000, 2000, 3000, 4000, 5000]
System.out.println(t.ceiling(2000));//2000
System.out.println(t.higher(4000));//5000
System.out.println(t.floor(1000));//1000
System.out.println(t.lower(3000));//2000
System.out.println(t.pollFirst());//1000
System.out.println(t.pollLast());//5000
System.out.println(t.descendingSet());//[4000, 3000, 2000]
System.out.println(t);//[2000, 3000, 4000]

}
NavigableMap:

It is the child interface of SortedMap.

It defines several methods for navigation purpose.

Methods():

 floorkey(e);
 lowerkey(e);
 celingkey(e);
 pollfirstEntry();
 polllastEntry();
 descendingMap();

package basic_problems;

import java.util.TreeMap;

public class navigablemapdemo {


public static void main(String[] args) {
TreeMap <String,String>t=new TreeMap<String,String>();
t.put("b", "banana");
t.put("c","cat");
t.put("a", "apple");
t.put("d","dog");
t.put("g", "gun");
System.out.println(t);//{a=apple, b=banana, c=cat, d=dog, g=gun}
System.out.println(t.ceilingKey("c"));//c
System.out.println(t.higherKey("e"));//g
System.out.println(t.floorKey("e"));//d
System.out.println(t.lowerKey("e"));//d
System.out.println(t.pollFirstEntry());//a=apple
System.out.println(t.pollLastEntry());//g=gun
System.out.println(t.descendingKeySet());//[d, c, b]
System.out.println(t);//{b=banana, c=cat, d=dog}

}
}

86
Collection’s:

Collections class defines several utility method for collection object like sorting
,searching, revising etc.

Methods:

1>public static void(list l);

to sort based on natural sorting order.

 In case list should compulsory contain homogenous and comparable


objects otherwise we will get run time exception ClassCastException.
 List should not contain null otherwise we will get NPE.

2>public static void sort(list l, comparator c);

 To sort based on customized sorting order.


package basic_problems;

import java.util.ArrayList;
import java.util.Collections;

public class Arraylistcollectiondemo {


public static void main(String[] args) {
ArrayList l=new ArrayList();
l.add("X");
l.add("A");
l.add("K");
l.add("N");
System.out.println(l);
// l.add(new Integer(10)); class cast exception
// l.add(null);//null pointer exception
System.out.println("before shorting:"+l);//[X, A, K, N]
Collections.sort(l);
System.out.println("after shorting:"+l);//[A, K, N, X]

}
Demo program to sort element of list according to customized sorting order.
package basic_problems;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;

public class customizeArraylistdemo {


public static void main(String[] args) {
ArrayList l =new ArrayList();
l.add("X");
l.add("A");
l.add("K");
l.add("N");

87
System.out.println("before sorting:"+l);//[X, A, K, N]
Collections.sort(l,new MyCOmparator());
System.out.println("After sorting:"+l);//[X, A, K, N]
}

}
class MyCOmparator implements Comparator{

@Override
public int compare(Object o1, Object o2) {
String s1=(String)o1;
String s2=(String)o2;

return 0;
}

Searching element of list:-

Collections class defines the following search methods

1>Public static int binaryserch(list l, object target );

 If the list is sorted according to default natural sorting order then we


have to use this method.

2>public static binarysearch(list l, object target ,Comparator C);

 We have to use this method if the list is sorted according to customized


sorting order.

Conclusions:

1> In the above search method internally, we will use binary search
algorithm.
2> Successful search returns index.
3> Unsuccessful search returns insertion point
4> Insertion point is the location where we can place target element in
sorted list
5> Before calling binary search method compulsory list should be store
otherwise we get unpredictable result
6> If the list is sorted according to comparator at the time of search
operation also we have to pass some comparator object otherwise we will
get unpredictable result.

88
X A M K a

-1 -2 -3 -4 -5 -6 insertion order

A K M X a
0 1 2 3 4 ----- index

Collections binarysearch(l,”X”) ;-3


Collections binarysearch(l,”J”);--- -2

package basic_problems;

import java.util.ArrayList;
import java.util.Collections;

public class Arraylistdemosearch {


public static void main(String[] args) {
ArrayList l=new ArrayList();
l.add("X");
l.add("A");
l.add("M");
l.add("K");
l.add("a");
System.out.println(l);//[X, A, M, K, a]
Collections.sort(l);
System.out.println(l);//[A, K, M, X, a]
System.out.println(Collections.binarySearch(l, "X"));//3
System.out.println(Collections.binarySearch(l, "J"));//-2
System.out.println(Collections.binarySearch(l, "c"));//-6

package revision;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class Arraylistdemo {


public static void main(String[] args) {
ArrayList<Object> l=new ArrayList<>();
l.add(15);
l.add(0);
l.add(20);
l.add(10);
l.add(5);
System.out.println(l);//[15, 0, 20, 10, 5]

89
Collections.sort(l,new MyComparator5());
System.out.println(l);//[20, 15, 10, 5, 0]
System.out.println(Collections.binarySearch(l, 10,new
MyComparator5()));//2
System.out.println(Collections.binarySearch(l, 13,new
MyComparator5()));//-3
System.out.println(Collections.binarySearch(l, 17,new
MyComparator5())); //unpredicate redult
}

}
class MyComparator5 implements Comparator{

@Override
public int compare(Object o1, Object o2) {
Integer i1=(Integer)o1;
Integer i2=(Integer)o2;
return i2.compareTo(i1);
}

 Successful search result range ->0 to 2


 Unsuccessfully search result range  -4 to -1
 Total result range -4 to 2

Note:- for the list of n element in the case of binary search method

 Successful search result range  o to n-1


 Unsuccessful search result range(n+1) to -1
 Total result range(n+1) to n-1

Reserving elements of list:-

Collection class defines the following reverse method to reverse element of list.

1>public Static void reverse(list l)


package revision;
import java.util.ArrayList;
import java.util.Collections;
public class reversedemo {
public static void main(String[] args) {
ArrayList <Object>l=new ArrayList<>();
l.add(15);
l.add(0);
l.add(20);
l.add(10);
l.add(5);
System.out.println(l);//[15, 0, 20, 10, 5]
Collections.reverse(l);
System.out.println(l);// [5, 10, 20, 0, 15

90
Reverse () vs reverseOrder() :

We can use reverse method to reverse order of element of list where as we can
reverse order to reversed comparator,

Example:

Comparator c1 = collection .reverseorder(Comparator c));


Descending order ascending order

Arrays class an utility class to define several utility methods for arrays object.

Arrays class defines the following sort methods to sort elements of primitive
and object type array.

1>public static void sort (primitive [] p);

 To sort according to natural shorting order.

2>public static void sort(object o);

 To sort according to natural sorting order

3>public static void sort(obj [] 0,Compartor c);

 To sort according to customized sorting order.

package revision;

import java.util.Arrays;
import java.util.Comparator;

public class demoo {


public static void main(String[] args) {
int []a= {10,5,20,11,6};
System.out.println("primitive Array before sorting");
for(int a1:a) {
System.out.println(a1);
}
Arrays.sort(a);
System.out.println("primitive array after sorting:");

for(int a1:a) {
System.out.println(a1);
}
String []s= {"A","Z","B"};
System.out.println("object array before sorting:");
for(String a2:s) {
System.out.println(a2);
}

91
Arrays.sort(s);
System.out.println("object array after sorting:");
for(String a1:s) {
System.out.println(a1);
}
Arrays.sort(s,new MyComp());
System.out.println("object array after sorting by the comparator");
for(String a1:s) {
System.out.println(a1);
}
}
}
class MyComp implements Comparator{

@Override
public int compare(Object o1, Object o2) {
String s1=o1.toString();
String s2=o2.toString();
return s2.compareTo(s1);
}

}
Output:
primitive Array before sorting
10
5
20
11
6
primitive array after sorting:
5
6
10
11
20
object array before sorting:
A
Z
B
object array after sorting:
A
B
Z
object array after sorting by the comparator
Z
B
A
Searching the element of arrays:

Arrays class defines the following binarysearch()

 Public Static int binarysearch(primitive [] p, primitive target);


 Public Static int binarysearch(object[]a, object target );
 Public Static int binarysearch(object []a, object target comparator c );

92
All rules of array class binary search method are exactly same as collections
class binarysearch().
package revision;

import java.util.Arrays;
import java.util.Comparator;

public class anoterdemo {


public static void main(String[] args) {
int [] a= {10,5,20,11,6};
Arrays.sort(a);
System.out.println(Arrays.binarySearch(a, 6));//1
System.out.println(Arrays.binarySearch(a, 14));//-5
String []s= {"A","Z","B"};
Arrays.sort(s);
System.out.println(Arrays.binarySearch(s, "Z"));//2
System.out.println(Arrays.binarySearch(s, "S"));//-3
Arrays.sort(s,new MyCOmparator44());
System.out.println(Arrays.binarySearch(s,"Z" ,new
MyCOmparator44()));//1
System.out.println(Arrays.binarySearch(s,"s" ,new
MyCOmparator44()));//1
System.out.println(Arrays.binarySearch(s, "N"));//-3
}

}
class MyCOmparator44 implements Comparator{

@Override
public int compare(Object o1, Object o2) {
String s1=o1.toString();
String s2=o2.toString();
return 0;
}

Conversion of array to list:

Public static list as list(obj [] a);

 Strictly speaking this method will not create any independent list object
for the existing array we are getting list view
String [] s={“A”,”Z”,”B”};
List l=Array.aslist(s);
 By using arrays reference if we perform any chance automatically that
change will be reflected to the array.
 By using list reference if we perform any change that change will be
reflected automatically to the array.
 By using list operation we cant perform any operation which varies the
size other wise we will get RE saying “unsupportedoperationException”

93
l.add(“M”);
l.remove(1); RE:” unsupportedoperationException”
l.set(1,”N”);

by using list reference we are not allowed to replace with heterogenous objects
otherwise we will get RE saying “ArrayStoreException”.
package revision;

import java.util.Arrays;
import java.util.List;

public class demoprogram {


public static void main(String[] args) {
String []s= {"A","Z","B"};
List l=Arrays.asList(s);
System.out.println(l);//[A, Z, B]
s[0]="k";
System.out.println(l);//[k, Z, B]
l.set(1,"L");
for(String s1:s) {
System.out.println(s1);//k L B
// l.add("utpal");//unsupportedoperationexception
// l.remove(2); //unsupportedoperationexception

// l.set(1, new Integer(10));ArraystoreException


}

94

You might also like