Strings and Collections
Strings and Collections
9>final vs immutability
10>Need of StringBuffer
<>ensureCapacity() <>trimToSize()
13>Need of 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:
2
String in String class equals () meant for content compression, where us in
StringBuffer equals() meant for reference compression.
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 s3=”Nithish”;
String s4=”Nithish“;
Nithish
s3 s4
S1
Nithish
Nithish
S2
s.concate(“Tulalu”);
s1=s.concate(“verma”);
Output:
Nithish
Nithish tulalu
4
String s1=new String(“spring”);
s1.concate(“fall”);
s2.concate(“summer”);
sopln(s1);
sopln(s2);
s1 gc
spring spring
Spring fall
s2
Spring winter
winter
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
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.
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.
>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?
}
Output:
NITHISH
abcd
Important methods of String class:
8
concate():
}
}
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
}
isEmpty();
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
}
}
}
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));
lastindexOf():
//public int lastIndexOf( 'char')
System.out.println(s.lastIndexOf('I'));
}
}
tolowercase():
4}
Op: tulalu nithish kumar
11
toUpperCase():
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());
}
import java.util.Scanner;
}
else if(name.equals("dark anime")) {
System.out.println("death_note");
}
else {
System.out.println("not valied input");
}
}
}
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
}
S1 China swami
China swami
S2
CHINA SWAMI
S3
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.
14
StringBuffer and StringBulider questions.
}
> ABCD
>ACD
>ACC (ANSWER)
>ABD
}
> true true
> false false
>true false
>false true (answer)
}
}
>12
>13
>55
>14 answer
}
} 5
15
Needs of StringBuffer:
If the content is not fixed and keep on changing String concept never
recommended to use.
StringBuffer:
s.concate(“kumar”)
1
public class refere {
16
2public class refere {
public static void main(String[] args) {
StringBuffer sb=new StringBuffer(100);
System.out.println(sb.capacity()); //100
}
Capacity=s.length(); 16+7
Sysout(capacity) /23
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()
}
}
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:
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.
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
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.
Non-primitive datatype are available in the form of class ,interface and Array
where they don’t have fixed range and capacity .
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 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
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);
}
ToString() Method:
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;
}
}
}
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.
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
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:
>>any parent class datatype can become user defined generalized datatype.
Object Object
Predefined
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
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.
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}
>>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;
28
Collection Framework:
Variables limitations in array
√--------------------- <> fixed in size
Student [] s=new[1000];
S[0]=new Student(); (√)
S[1]=new Customer(); error: incompatible found: customer required :Student
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.
>>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.
29
<1>Collections:
>>being a programmer ,we are responsible to use those methods, we are not
responsible to implement those methods .
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
>>Collection interface defines the most common methods which are defined for
any collection object.
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):
Note: in 1.2 version vector and stack classes are modified to implement list
interface.
<3>Set(i):
HashSet 1.2v
first implement classes
32
It is the child interface of collection.
<4>SortedSet(I):
Collection(I) 1.2 v
Set(i) 1.2 v
SortedSet(i) 1.2 v
NagviableSet(i) 1.6v
33
<5>NagvigableSet(i):
List(i) Set(i)
Duplicates are allowed duplicates are not allowed
insertion order preserved insertion order not preserved
<6> Queue(i)
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
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:
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) :
36
Comparator, Comparable & Cursor :
1.Collections
2.Arrays
Legacy characters:
Interview Questions:
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.
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
38
<> Collection Vs Collections:
Collections interface defines the most common methods which are applicable
for any collection object.
List vs Collection: -
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: -
To replace the element present at specific index with provided objects and
returns old object.
39
int indexOf(Object O);
ListIterator listIterator();
Array list:
Constructor:
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.
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);
import java.util.ArrayList;
}
}
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.
41
package basic_problems;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.RandomAccess;
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.
Example:
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.
LinkedList:
Double linklist
A B C
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:
import java.util.LinkedList;
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:
Constructor:
Once vector reaches its max capacity then a new vector object will be created
with new 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.
Creates a equivalent vector object for the given collection .this vector object is
meant for inter conversion between collection objects.
add(Object o);Collection
add(int index, Object o) list
add Element(Object o);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;
import java.util.Vector;
47
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, A]
Stack:
Constructor of stack:
2.Object pop();
3.Object peek();
4.boolean empty();
48
import java.util.Stack;
}
Output:
[A, B, C]
3
-1
If we want to get objects one by one from the collections then we should go for
cursors.
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.
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;
}
}
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.
Example:
Methods of Iterator:
50
Public object next();
Public void remove();
package basic_problems;
import java.util.ArrayList;
import java.util.Iterator;
Limitation of Iterator:
ListIterator:-
51
By using ListIterator, we can perform replacement and addition of new objects.
ListIterator is the child Interface of Iterator and hence all method which are
present in Iterator. By default, available to the ListIterator.
52
package basic_problems;
import java.util.LinkedList;
import java.util.ListIterator;
}
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.
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;
54
Set:
Set
treeSet
>set interface doesn’t contain any new method and we have to use only collection
interface methods.
HashSet:
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;
55
}
Output:
false
[null, Kumar, Nithish]
Constructor:
create an empty HashSet object with default initial capacity 16 and default
fill ratio 0.75.
creates an empty HashSet object with specified initial capacity and default
fill ratio 0.75.
create an equivalent HashSet for the given collection this constructor meant
for interconversion between collection.
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;
}
Output:
false
[null, B, C, D,: Z, 10] output depends on hash table
56
LinkedHashSet:
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;
}
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:
.w
57
3> SortedSet headset(object obj) ;
Comparator Comparator()
NOTE:- that default natural shorting order for numbers ascending order for
string alphabetical order.
import java.util.SortedSet;
import java.util.TreeSet;
Output:
100
120
[100, 101, 104]
[106, 115, 120]
[101, 104, 106]
null
58
TreeSet (implementation class):
Constructor:
creates an empty TreeSet object where the element will inserted according
to default natural shorting order.
}
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.
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//
Comparable(I):
compareTo();
Syntax:
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
}
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.
Where as
61
Comparator: comparator present in java util package and it defines two method.
Compare();
equals();
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;
}
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;
@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;
}
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.
import java.util.Comparator;
import java.util.TreeSet;
}
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:
package basic_problems;
import java.util.Comparator;
import java.util.TreeSet;
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
Map:
68
Map interface methods:
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.
3>Object get(Object key);// return the value associated with specified key.
4>object remove(object key );// remove the entry associated with specified
key.
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.
HashMap:-
Constructor of HashMap:-
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;
}
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;
73
IdentityHashMap:-
package basic_problems;
import java.util.HashMap;
import java.util.IdentityHashMap;
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:-
In the case of HashMap even though object does not have any reference
variable it is not eligible for garbage collection(GC).
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.
import java.util.WeakHashMap;
class temp1{
public String toString() {
return "Temp1";
}
public void finalize() {
System.out.println("Finalize method called");
}
}
Output:
{Temp1=utpal}
Finalize method called
{}
76
SortedMap:-
Methods of SortedMap:-
Object firstKey();
Object LastKey();
SortedMap headMap (Object Key);
SortedMap tailMap(Object Key);
SortedMap submap(Object key1,object key2);
Comparator comparator();
TreeMap:-
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.
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:-
78
Demo program for customize shorting order for TreeMap.
import java.util.Comparator;
import java.util.TreeMap;
@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:
Constructors :
Creates an empty HashTable object with default initial capacity 11 and fill ratio
75%.
79
2>HashTable h=new HashTable(int initial capacity);
Properties:
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.
Constructor:
Methods:
To set a new propriety if the specified property already available then old value
will represent with new and return old value.
To get value associated with the specified property not available then this
method will return null.
80
4>void load(inputStream is);
> To load properties from properties file into java properties object.
Load()
Store()
import java.util.Properties;
import java.util.Properties;
81
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
linked Blocked Q
Method:
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:
Constructor:
creates empty priority Queue object default capacity 11 and all object will
be inserted according to default natural sorting order.
83
Demo for default natural shorting order
package basic_problems;
import java.util.PriorityQueue;
}
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;
}
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:
navigable set
navigable map
navigable set:
Methods:
1>Floor(e);
2>lower(e);
3>celing(e);
4>higher(e);
5>pollfirst();
6>poolLast();
7> descendingSet();
import java.util.TreeSet;
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:
Methods():
floorkey(e);
lowerkey(e);
celingkey(e);
pollfirstEntry();
polllastEntry();
descendingMap();
package basic_problems;
import java.util.TreeMap;
}
}
86
Collection’s:
Collections class defines several utility method for collection object like sorting
,searching, revising etc.
Methods:
import java.util.ArrayList;
import java.util.Collections;
}
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;
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;
}
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
package basic_problems;
import java.util.ArrayList;
import java.util.Collections;
package revision;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
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);
}
Note:- for the list of n element in the case of binary search method
Collection class defines the following reverse method to reverse element of list.
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:
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.
package revision;
import java.util.Arrays;
import java.util.Comparator;
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:
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;
}
class MyCOmparator44 implements Comparator{
@Override
public int compare(Object o1, Object o2) {
String s1=o1.toString();
String s2=o2.toString();
return 0;
}
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;
94