SlideShare a Scribd company logo
Java/J2EE Programming Training
Objects and Collections &
Garbage Collection
Page 1Classification: Restricted
Agenda
• Objects
• Collections
• Garbage Collection
Page 2Classification: Restricted
Objective
• Distinguish between correct and incorrect implementations of hashcode
methods.
• Make appropriate selection of collection classes/interfaces to suit
specified behavior requirements.
Page 3Classification: Restricted
hashcode()
• The hashcode value of an object gives a number which can be used to in
effect to index objects in a collection. A collection class can group its
objects by their hashcodes
• If two objects are equal as given the equals() method, their hashcodes
should be the same. So whenever equals() is overridden, hashcode() also
should be implemented
• The reverse is not required i.e. two objects that are not equal can have
the same hashcode. This makes sense, as it is not always possible to
ensure unique hashcodes. However, it is desirable to have distinct
hashcodes as this can improve performance.
Eg:
public int hashcode() { return (int)(value^5); }
Page 4Classification: Restricted
equals()
The equals method implements an equivalence relation:
• It is reflexive: for any reference value x, x.equals(x) should return true.
• It is symmetric: for any reference values x and y, x.equals(y) should
return true if and only if y.equals(x) returns true.
• It is transitive: for any reference values x, y, and z, if x.equals(y) returns
true and y.equals(z) returns true, then x.equals(z) should return true.
• It is consistent: for any reference values x and y, multiple invocations of
x.equals(y) consistently return true or consistently return false,
provided no information used in equals comparisons on the object is
modified.
• For any non-null reference value x, x.equals(null) should return false.
Page 5Classification: Restricted
Condition Required Not Required (But
Allowed)
x.equals(y)==true x.hashCode()==y.
hashCode()
x.hashCode()==y.
hashCode()
x.equals(y)==true
x.equals(y)==false No hashCode
requirements
x.hashCode()!=y.h
ashCode()
x.equals(y)==false
The hashCode() Contract
Page 6Classification: Restricted
Collection
• A collection is a data structure in which objects are stored
• The collections can grow and shrink dynamically
• The collection classes are in the java.util package
• Collections are of 3 kinds – Lists, Sets and Maps
• The Collection interface is the root of the collection hierarchy. Some
Collection implementations allow duplicate elements and others do not.
Some are ordered and others unordered.
• List and Set interfaces extend the Collection interface, but Map interface
does not
Page 7Classification: Restricted
The collections class and interface hierarchy
Collection
Set
List
SortedSet
HashSet LinkedHashSet TreeSet LinkedList Vector ArrayList
Indicates Implementation
Indicates Inheritance
Page 8Classification: Restricted
Map
SortedMap
Hashtable LinkedHashMap HashMap TreeMap
Indicates Implementation
Indicates Inheritance
Page 9Classification: Restricted
Set
• A Set is a collection that cannot contain duplicate elements.The Set
interface extends Collection and contains no methods other than those
inherited from Collection.
• It adds the restriction that duplicate elements are prohibited.
• The classes implementing Set interface are:
HashSet – Assures no duplicates, not ordered
TreeSet- No duplicates, gives elements in the sorted order
LinkedHashSet- No duplicates, insertion order or last accessed order is
maintained
Page 10Classification: Restricted
Example
Eg:
import java.util.*;
public class LinkTest {
public static void main(String args[]) {
LinkedHashSet linkSet=new LinkedHashSet();
linkSet.add("mango");
linkSet.add("apple");
linkSet.add(“mango”);
linkSet.add("banana");
Iterator i=linkSet.iterator();
while(i.hasNext())
System.out.println(i.next());
}
}
Page 11Classification: Restricted
List
• A List is an ordered Collection, elements are stored in the order in which
they were added
• Lists may contain duplicate elements.
• List allows positional access and search
• Classes implementing List interface are
ArrayList – Fast iteration and fast random access
Vector-Similar to ArrayList, slower than it, synchronized
LinkedList-Good for adding elements at the beginning or end, used for
implementing stacks and queues
Page 12Classification: Restricted
Example
import java.util.*;
public class ListTest {
public static void main(String args[]) {
ArrayList list=new ArrayList();
list.add("mango");
list.add("apple");
list.add(“mango”);
list.add("banana");
Iterator i=list.iterator();
while(i.hasNext())
System.out.println("Fruit is "+i.next());
}
}
Page 13Classification: Restricted
Map
• A Map is an object that maps keys to values.
• A map cannot contain duplicate keys: Each key can map to at most one
value.
Classes implementing Map interface are:
HashMap – Faster updates, allows one null key, many null values
Hashtable- Similar to HashMap, but slower, synchronized, does not allow
null keys and values
LinkedHashMap – Faster iterations, iterates by insertion or last accessed
order. Allows one null key and many null values
TreeMap- A sorted map, in natural order of keys
Page 14Classification: Restricted
Example
import java.util.*;
class TreeMapDemo {
public static void main(String args[])
{
TreeMap tm=new TreeMap();
tm.put("India",new Integer(100));
tm.put("USA",new Integer(7));
tm.put("Pakistan",new Integer(2));
System.out.println(tm);
}
}
Page 15Classification: Restricted
Collection Interface Concrete Implementation Classes
Class Map Set List Ordered Sorted
HashMap X No No
Hashtable X No No
TreeMap X Sorted By natural order or
custom comparison
rules
LinkedHashMap X By insertion order
or last access order
No
HashSet X No No
TreeSet X Sorted By natural order or
custom comparison
rules
LinkedHashSet X By insertion order
or last access order
No
ArrayList X By index No
Vector X By index No
LinkedList X By index No
Page 16Classification: Restricted
Extra Points to Remember
• It is incorrect to involve a random number directly when computing the
hashcode, because it would not return the same hashcode for multiple
invocations of the method
• Hashcode of a null element is defined as zero
• StringBuffer class does not override equals() and hence inherits the default
implementation given in Object class
• For wrapper classes and String class, equals() method returns false if the
argument type is different from that of the invoking object
Eg: Integer i=new Integer(7);
Float f=new Float(7);
if(i.equals(f)) // gives false
System.out.println(“Equal”);
Page 17Classification: Restricted
Objectives
• State the behavior that is guaranteed by the garbage collection system.
• Write code that explicitly makes objects eligible for garbage collection.
• Recognize the point in a piece of source code at which an object
becomes eligible for garbage collection.
Page 18Classification: Restricted
Garbage Collection
• Garbage collection refers to the automatic memory management
provided by Java
• The Java runtime environment has a garbage collector that periodically
frees the memory used by objects that are no longer needed.
• The garbage collector runs in a low priority thread and it’s
implementation is specific to the JVM
• An object is considered eligible for garbage collection when no live
thread can reach it
Page 19Classification: Restricted
Requesting for Garbage Collection
• Garbage collection cannot be forced and there is no guarantee as to
when the garbage collector thread will run
• You can request for garbage collection to be initiated, but the request
may or may not be granted
• To request for garbage collection, you can call any of these methods
• System.gc()
• Runtime.getRuntime().gc()
• If available memory is too low, the garbage collector will surely run
before it throws OutOfMemoryException
Page 20Classification: Restricted
Making objects eligible for GC
• An object can become eligible for Garbage Collection in different ways
Objects which are created locally in a method are eligible when the
method returns, unless they are exported out of the method (returned
or thrown as an exception)
If the reference variable that refers to the object is set to null, it
becomes eligible
If the reference variable that refers to the object is made to refer to
some other object, it becomes eligible
Objects which refer to each other can still be eligible, if no live thread
can access either of them
Page 21Classification: Restricted
Examples
• Eg: // Objects created in a method
public class Test
{ public static void main(String args[]) {
String s=getDateString();
System.out.println(“Date string is “+s);
}
public String getDateString() {
Date date=new Date();
return date.toString();
}
}
/* The object date is eligible for garbage collection after the method
returns */
Page 22Classification: Restricted
Examples
• Eg: // Reassigning reference variables
public class TestGC
{ public static void main(String [] args) {
Object a = new Integer(7);
Object b = new StringBuffer("Java");
a = b;
b = null;
}
}
/* Here only the Integer object is eligible for collection
Page 23Classification: Restricted
Object Finalization
• The finalize() method defined in the class Object is inherited by all classes.
protected void finalize() throws Throwable
• This method is called just before the object is garbage collected, so the
object can perform any cleanup action here
• The finalize() method will be invoked only once in the lifetime of an object
• You can write code in the finalize() method which can prevent the object
from being garbage collected.
Page 24Classification: Restricted
Extra points to remember…
• The garbage collection algorithm used is specific to each JVM
• You can make an object uneligible for garbage collection, from its finalize()
method. But the garbage collector will not run finalize() for this object again
• A finalizer can catch and throw exceptions
• Any exception thrown but not caught in the finalize() method is ignored by
the garbage collector
• It cannot be guaranteed that the garbage collector will run, so finalize()
method may never be called
• There is no guarantee on the order in which objects will be garbage collected
Page 25Classification: Restricted
Thank You

More Related Content

What's hot

Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection framework
ankitgarg_er
 
Scala Collections : Java 8 on Steroids
Scala Collections : Java 8 on SteroidsScala Collections : Java 8 on Steroids
Scala Collections : Java 8 on Steroids
François Garillot
 
Java Collections
Java  Collections Java  Collections
Session 14 - Object Class
Session 14 - Object ClassSession 14 - Object Class
Session 14 - Object Class
PawanMM
 
Collections In Java
Collections In JavaCollections In Java
Collections In JavaBinoj T E
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & sets
RatnaJava
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
Minal Maniar
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
Prof. Erwin Globio
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
Shalabh Chaudhary
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
Riccardo Cardin
 
Generics
GenericsGenerics
Java collections notes
Java collections notesJava collections notes
Java collections notes
Surendar Meesala
 
Java collection
Java collectionJava collection
Java collection
Arati Gadgil
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
CPD INDIA
 
Java Collections API
Java Collections APIJava Collections API
Java Collections API
Alex Miller
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structures
agorolabs
 
Collections in Java
Collections in JavaCollections in Java
Collections in Java
Khasim Cise
 
Object Class
Object ClassObject Class
Object Class
RatnaJava
 
Collections Java e Google Collections
Collections Java e Google CollectionsCollections Java e Google Collections
Collections Java e Google Collections
André Faria Gomes
 

What's hot (20)

Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection framework
 
Scala Collections : Java 8 on Steroids
Scala Collections : Java 8 on SteroidsScala Collections : Java 8 on Steroids
Scala Collections : Java 8 on Steroids
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Session 14 - Object Class
Session 14 - Object ClassSession 14 - Object Class
Session 14 - Object Class
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & sets
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 
Generics
GenericsGenerics
Generics
 
Java collections notes
Java collections notesJava collections notes
Java collections notes
 
Java collection
Java collectionJava collection
Java collection
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 
Java Collections API
Java Collections APIJava Collections API
Java Collections API
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structures
 
Collections in Java
Collections in JavaCollections in Java
Collections in Java
 
Javasession7
Javasession7Javasession7
Javasession7
 
Object Class
Object ClassObject Class
Object Class
 
Collections Java e Google Collections
Collections Java e Google CollectionsCollections Java e Google Collections
Collections Java e Google Collections
 

Similar to Java Collection

Collections Training
Collections TrainingCollections Training
Collections Training
Ramindu Deshapriya
 
Joshua bloch effect java chapter 3
Joshua bloch effect java   chapter 3Joshua bloch effect java   chapter 3
Joshua bloch effect java chapter 3
Kamal Mukkamala
 
Java Tutorials
Java Tutorials Java Tutorials
Java Tutorials
Woxa Technologies
 
java training faridabad
java training faridabadjava training faridabad
java training faridabad
Woxa Technologies
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharma
Sandesh Sharma
 
Collections
CollectionsCollections
Collections
bsurya1989
 
Collections in java
Collections in javaCollections in java
Collections in javakejpretkopet
 
Java Hands-On Workshop
Java Hands-On WorkshopJava Hands-On Workshop
Java Hands-On Workshop
Arpit Poladia
 
Java for newcomers
Java for newcomersJava for newcomers
Java for newcomers
Amith jayasekara
 
Best practices in Java
Best practices in JavaBest practices in Java
Best practices in Java
Mudit Gupta
 
Collections and generic class
Collections and generic classCollections and generic class
Collections and generic class
ifis
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshan
Zeeshan Khan
 
Lecture 24
Lecture 24Lecture 24
Lecture 24
Debasish Pratihari
 
C# Non generics collection
C# Non generics collectionC# Non generics collection
C# Non generics collection
Prem Kumar Badri
 
Topic-G-JavaCollections Framework.ppt
Topic-G-JavaCollections    Framework.pptTopic-G-JavaCollections    Framework.ppt
Topic-G-JavaCollections Framework.ppt
swapnilslide2019
 
Core & advanced java classes in mumbai
Core & advanced java classes in mumbaiCore & advanced java classes in mumbai
Core & advanced java classes in mumbai
Vibrant Technologies & Computers
 
Java tutorial part 4
Java tutorial part 4Java tutorial part 4
Java tutorial part 4
Mumbai Academisc
 
STRINGS IN JAVA
STRINGS IN JAVASTRINGS IN JAVA

Similar to Java Collection (20)

Collections
CollectionsCollections
Collections
 
Collections Training
Collections TrainingCollections Training
Collections Training
 
Joshua bloch effect java chapter 3
Joshua bloch effect java   chapter 3Joshua bloch effect java   chapter 3
Joshua bloch effect java chapter 3
 
Java Tutorials
Java Tutorials Java Tutorials
Java Tutorials
 
java training faridabad
java training faridabadjava training faridabad
java training faridabad
 
Collections
CollectionsCollections
Collections
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharma
 
Collections
CollectionsCollections
Collections
 
Collections in java
Collections in javaCollections in java
Collections in java
 
Java Hands-On Workshop
Java Hands-On WorkshopJava Hands-On Workshop
Java Hands-On Workshop
 
Java for newcomers
Java for newcomersJava for newcomers
Java for newcomers
 
Best practices in Java
Best practices in JavaBest practices in Java
Best practices in Java
 
Collections and generic class
Collections and generic classCollections and generic class
Collections and generic class
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshan
 
Lecture 24
Lecture 24Lecture 24
Lecture 24
 
C# Non generics collection
C# Non generics collectionC# Non generics collection
C# Non generics collection
 
Topic-G-JavaCollections Framework.ppt
Topic-G-JavaCollections    Framework.pptTopic-G-JavaCollections    Framework.ppt
Topic-G-JavaCollections Framework.ppt
 
Core & advanced java classes in mumbai
Core & advanced java classes in mumbaiCore & advanced java classes in mumbai
Core & advanced java classes in mumbai
 
Java tutorial part 4
Java tutorial part 4Java tutorial part 4
Java tutorial part 4
 
STRINGS IN JAVA
STRINGS IN JAVASTRINGS IN JAVA
STRINGS IN JAVA
 

More from DeeptiJava

Generating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Status CodesGenerating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Status Codes
DeeptiJava
 
Java Generics
Java GenericsJava Generics
Java Generics
DeeptiJava
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception Handling
DeeptiJava
 
Java OOPs
Java OOPs Java OOPs
Java OOPs
DeeptiJava
 
Java Access Specifier
Java Access SpecifierJava Access Specifier
Java Access Specifier
DeeptiJava
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
DeeptiJava
 
Java Thread
Java ThreadJava Thread
Java Thread
DeeptiJava
 
Java Inner Class
Java Inner ClassJava Inner Class
Java Inner Class
DeeptiJava
 
JSP Part 2
JSP Part 2JSP Part 2
JSP Part 2
DeeptiJava
 
JSP Part 1
JSP Part 1JSP Part 1
JSP Part 1
DeeptiJava
 
Java I/O
Java I/OJava I/O
Java I/O
DeeptiJava
 
Java Hibernate Basics
Java Hibernate BasicsJava Hibernate Basics
Java Hibernate Basics
DeeptiJava
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
DeeptiJava
 

More from DeeptiJava (13)

Generating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Status CodesGenerating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Status Codes
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception Handling
 
Java OOPs
Java OOPs Java OOPs
Java OOPs
 
Java Access Specifier
Java Access SpecifierJava Access Specifier
Java Access Specifier
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
 
Java Thread
Java ThreadJava Thread
Java Thread
 
Java Inner Class
Java Inner ClassJava Inner Class
Java Inner Class
 
JSP Part 2
JSP Part 2JSP Part 2
JSP Part 2
 
JSP Part 1
JSP Part 1JSP Part 1
JSP Part 1
 
Java I/O
Java I/OJava I/O
Java I/O
 
Java Hibernate Basics
Java Hibernate BasicsJava Hibernate Basics
Java Hibernate Basics
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
 

Recently uploaded

ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
CatarinaPereira64715
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
Abida Shariff
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 

Recently uploaded (20)

ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 

Java Collection

  • 1. Java/J2EE Programming Training Objects and Collections & Garbage Collection
  • 2. Page 1Classification: Restricted Agenda • Objects • Collections • Garbage Collection
  • 3. Page 2Classification: Restricted Objective • Distinguish between correct and incorrect implementations of hashcode methods. • Make appropriate selection of collection classes/interfaces to suit specified behavior requirements.
  • 4. Page 3Classification: Restricted hashcode() • The hashcode value of an object gives a number which can be used to in effect to index objects in a collection. A collection class can group its objects by their hashcodes • If two objects are equal as given the equals() method, their hashcodes should be the same. So whenever equals() is overridden, hashcode() also should be implemented • The reverse is not required i.e. two objects that are not equal can have the same hashcode. This makes sense, as it is not always possible to ensure unique hashcodes. However, it is desirable to have distinct hashcodes as this can improve performance. Eg: public int hashcode() { return (int)(value^5); }
  • 5. Page 4Classification: Restricted equals() The equals method implements an equivalence relation: • It is reflexive: for any reference value x, x.equals(x) should return true. • It is symmetric: for any reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true. • It is transitive: for any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true. • It is consistent: for any reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the object is modified. • For any non-null reference value x, x.equals(null) should return false.
  • 6. Page 5Classification: Restricted Condition Required Not Required (But Allowed) x.equals(y)==true x.hashCode()==y. hashCode() x.hashCode()==y. hashCode() x.equals(y)==true x.equals(y)==false No hashCode requirements x.hashCode()!=y.h ashCode() x.equals(y)==false The hashCode() Contract
  • 7. Page 6Classification: Restricted Collection • A collection is a data structure in which objects are stored • The collections can grow and shrink dynamically • The collection classes are in the java.util package • Collections are of 3 kinds – Lists, Sets and Maps • The Collection interface is the root of the collection hierarchy. Some Collection implementations allow duplicate elements and others do not. Some are ordered and others unordered. • List and Set interfaces extend the Collection interface, but Map interface does not
  • 8. Page 7Classification: Restricted The collections class and interface hierarchy Collection Set List SortedSet HashSet LinkedHashSet TreeSet LinkedList Vector ArrayList Indicates Implementation Indicates Inheritance
  • 9. Page 8Classification: Restricted Map SortedMap Hashtable LinkedHashMap HashMap TreeMap Indicates Implementation Indicates Inheritance
  • 10. Page 9Classification: Restricted Set • A Set is a collection that cannot contain duplicate elements.The Set interface extends Collection and contains no methods other than those inherited from Collection. • It adds the restriction that duplicate elements are prohibited. • The classes implementing Set interface are: HashSet – Assures no duplicates, not ordered TreeSet- No duplicates, gives elements in the sorted order LinkedHashSet- No duplicates, insertion order or last accessed order is maintained
  • 11. Page 10Classification: Restricted Example Eg: import java.util.*; public class LinkTest { public static void main(String args[]) { LinkedHashSet linkSet=new LinkedHashSet(); linkSet.add("mango"); linkSet.add("apple"); linkSet.add(“mango”); linkSet.add("banana"); Iterator i=linkSet.iterator(); while(i.hasNext()) System.out.println(i.next()); } }
  • 12. Page 11Classification: Restricted List • A List is an ordered Collection, elements are stored in the order in which they were added • Lists may contain duplicate elements. • List allows positional access and search • Classes implementing List interface are ArrayList – Fast iteration and fast random access Vector-Similar to ArrayList, slower than it, synchronized LinkedList-Good for adding elements at the beginning or end, used for implementing stacks and queues
  • 13. Page 12Classification: Restricted Example import java.util.*; public class ListTest { public static void main(String args[]) { ArrayList list=new ArrayList(); list.add("mango"); list.add("apple"); list.add(“mango”); list.add("banana"); Iterator i=list.iterator(); while(i.hasNext()) System.out.println("Fruit is "+i.next()); } }
  • 14. Page 13Classification: Restricted Map • A Map is an object that maps keys to values. • A map cannot contain duplicate keys: Each key can map to at most one value. Classes implementing Map interface are: HashMap – Faster updates, allows one null key, many null values Hashtable- Similar to HashMap, but slower, synchronized, does not allow null keys and values LinkedHashMap – Faster iterations, iterates by insertion or last accessed order. Allows one null key and many null values TreeMap- A sorted map, in natural order of keys
  • 15. Page 14Classification: Restricted Example import java.util.*; class TreeMapDemo { public static void main(String args[]) { TreeMap tm=new TreeMap(); tm.put("India",new Integer(100)); tm.put("USA",new Integer(7)); tm.put("Pakistan",new Integer(2)); System.out.println(tm); } }
  • 16. Page 15Classification: Restricted Collection Interface Concrete Implementation Classes Class Map Set List Ordered Sorted HashMap X No No Hashtable X No No TreeMap X Sorted By natural order or custom comparison rules LinkedHashMap X By insertion order or last access order No HashSet X No No TreeSet X Sorted By natural order or custom comparison rules LinkedHashSet X By insertion order or last access order No ArrayList X By index No Vector X By index No LinkedList X By index No
  • 17. Page 16Classification: Restricted Extra Points to Remember • It is incorrect to involve a random number directly when computing the hashcode, because it would not return the same hashcode for multiple invocations of the method • Hashcode of a null element is defined as zero • StringBuffer class does not override equals() and hence inherits the default implementation given in Object class • For wrapper classes and String class, equals() method returns false if the argument type is different from that of the invoking object Eg: Integer i=new Integer(7); Float f=new Float(7); if(i.equals(f)) // gives false System.out.println(“Equal”);
  • 18. Page 17Classification: Restricted Objectives • State the behavior that is guaranteed by the garbage collection system. • Write code that explicitly makes objects eligible for garbage collection. • Recognize the point in a piece of source code at which an object becomes eligible for garbage collection.
  • 19. Page 18Classification: Restricted Garbage Collection • Garbage collection refers to the automatic memory management provided by Java • The Java runtime environment has a garbage collector that periodically frees the memory used by objects that are no longer needed. • The garbage collector runs in a low priority thread and it’s implementation is specific to the JVM • An object is considered eligible for garbage collection when no live thread can reach it
  • 20. Page 19Classification: Restricted Requesting for Garbage Collection • Garbage collection cannot be forced and there is no guarantee as to when the garbage collector thread will run • You can request for garbage collection to be initiated, but the request may or may not be granted • To request for garbage collection, you can call any of these methods • System.gc() • Runtime.getRuntime().gc() • If available memory is too low, the garbage collector will surely run before it throws OutOfMemoryException
  • 21. Page 20Classification: Restricted Making objects eligible for GC • An object can become eligible for Garbage Collection in different ways Objects which are created locally in a method are eligible when the method returns, unless they are exported out of the method (returned or thrown as an exception) If the reference variable that refers to the object is set to null, it becomes eligible If the reference variable that refers to the object is made to refer to some other object, it becomes eligible Objects which refer to each other can still be eligible, if no live thread can access either of them
  • 22. Page 21Classification: Restricted Examples • Eg: // Objects created in a method public class Test { public static void main(String args[]) { String s=getDateString(); System.out.println(“Date string is “+s); } public String getDateString() { Date date=new Date(); return date.toString(); } } /* The object date is eligible for garbage collection after the method returns */
  • 23. Page 22Classification: Restricted Examples • Eg: // Reassigning reference variables public class TestGC { public static void main(String [] args) { Object a = new Integer(7); Object b = new StringBuffer("Java"); a = b; b = null; } } /* Here only the Integer object is eligible for collection
  • 24. Page 23Classification: Restricted Object Finalization • The finalize() method defined in the class Object is inherited by all classes. protected void finalize() throws Throwable • This method is called just before the object is garbage collected, so the object can perform any cleanup action here • The finalize() method will be invoked only once in the lifetime of an object • You can write code in the finalize() method which can prevent the object from being garbage collected.
  • 25. Page 24Classification: Restricted Extra points to remember… • The garbage collection algorithm used is specific to each JVM • You can make an object uneligible for garbage collection, from its finalize() method. But the garbage collector will not run finalize() for this object again • A finalizer can catch and throw exceptions • Any exception thrown but not caught in the finalize() method is ignored by the garbage collector • It cannot be guaranteed that the garbage collector will run, so finalize() method may never be called • There is no guarantee on the order in which objects will be garbage collected