SlideShare a Scribd company logo
1 of 26
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 (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

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
 
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
 
Java OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - CollectionJava OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - Collection
 

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 CodesDeeptiJava
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception HandlingDeeptiJava
 
Java Access Specifier
Java Access SpecifierJava Access Specifier
Java Access SpecifierDeeptiJava
 
Java Inner Class
Java Inner ClassJava Inner Class
Java Inner ClassDeeptiJava
 
Java Hibernate Basics
Java Hibernate BasicsJava Hibernate Basics
Java Hibernate BasicsDeeptiJava
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to JavaDeeptiJava
 

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

Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 

Recently uploaded (20)

Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 

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