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

PPSX
Collections - Maps
PPSX
Object Class
PPSX
Collections - Lists, Sets
PPSX
Collections - Array List
PPTX
Session 17 - Collections - Lists, Sets
PPSX
Collections - Sorting, Comparing Basics
PPTX
Session 20 - Collections - Maps
PPTX
Session 15 - Collections - Array List
Collections - Maps
Object Class
Collections - Lists, Sets
Collections - Array List
Session 17 - Collections - Lists, Sets
Collections - Sorting, Comparing Basics
Session 20 - Collections - Maps
Session 15 - Collections - Array List

What's hot (20)

PDF
Java Collection framework
PDF
Scala Collections : Java 8 on Steroids
PPTX
Session 14 - Object Class
PDF
Collections In Java
PPTX
Collections - Lists & sets
PDF
5 collection framework
PDF
Java Collections Tutorials
PDF
Collections in Java Notes
PPTX
Java - Collections framework
DOCX
Java collections notes
PPT
Java collection
PPT
Collection Framework in java
PDF
Java Collections API
PPTX
Java 103 intro to java data structures
PPT
Collections in Java
PPTX
Javasession7
PPTX
Object Class
PDF
Collections Java e Google Collections
Java Collection framework
Scala Collections : Java 8 on Steroids
Session 14 - Object Class
Collections In Java
Collections - Lists & sets
5 collection framework
Java Collections Tutorials
Collections in Java Notes
Java - Collections framework
Java collections notes
Java collection
Collection Framework in java
Java Collections API
Java 103 intro to java data structures
Collections in Java
Javasession7
Object Class
Collections Java e Google Collections
Ad

Similar to Java Collection (20)

PPTX
Session 18 - Review Session and Attending Java Interviews
PPSX
Review Session and Attending Java Interviews
PPSX
Review Session - Part -2
PPTX
Java Hands-On Workshop
PPT
description of Collections, seaching & Sorting
PDF
JAVA PROGRAMMING - The Collections Framework
PPTX
Session 19 - Review Session
PPTX
Collections
PPSX
Core Java for Selenium
PPTX
Collections Training
PPTX
Java Access Specifier
PPTX
More topics on Java
PPTX
Review Session and Attending Java Interviews
PPTX
Introduction to Java
PPTX
Introduction to Java
PPTX
Session 38 - Core Java (New Features) - Part 1
PDF
Java 8 new features or the ones you might actually use
PDF
07 java collection
PPTX
oop lecture framework,list,maps,collection
PPT
Java Tutorial
Session 18 - Review Session and Attending Java Interviews
Review Session and Attending Java Interviews
Review Session - Part -2
Java Hands-On Workshop
description of Collections, seaching & Sorting
JAVA PROGRAMMING - The Collections Framework
Session 19 - Review Session
Collections
Core Java for Selenium
Collections Training
Java Access Specifier
More topics on Java
Review Session and Attending Java Interviews
Introduction to Java
Introduction to Java
Session 38 - Core Java (New Features) - Part 1
Java 8 new features or the ones you might actually use
07 java collection
oop lecture framework,list,maps,collection
Java Tutorial
Ad

More from DeeptiJava (11)

PPT
Generating the Server Response: HTTP Status Codes
PPTX
Java Generics
PPTX
Java Exception Handling
PPTX
Java OOPs
PPTX
Java JDBC
PPTX
Java Thread
PPTX
Java Inner Class
PPT
JSP Part 2
PPT
JSP Part 1
PPTX
Java I/O
PPT
Java Hibernate Basics
Generating the Server Response: HTTP Status Codes
Java Generics
Java Exception Handling
Java OOPs
Java JDBC
Java Thread
Java Inner Class
JSP Part 2
JSP Part 1
Java I/O
Java Hibernate Basics

Recently uploaded (20)

PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
Getting Started with Data Integration: FME Form 101
PDF
A comparative study of natural language inference in Swahili using monolingua...
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
TLE Review Electricity (Electricity).pptx
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Empathic Computing: Creating Shared Understanding
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Encapsulation theory and applications.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PPTX
Tartificialntelligence_presentation.pptx
PPTX
Spectroscopy.pptx food analysis technology
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PDF
Encapsulation_ Review paper, used for researhc scholars
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Getting Started with Data Integration: FME Form 101
A comparative study of natural language inference in Swahili using monolingua...
Diabetes mellitus diagnosis method based random forest with bat algorithm
TLE Review Electricity (Electricity).pptx
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Per capita expenditure prediction using model stacking based on satellite ima...
Empathic Computing: Creating Shared Understanding
Accuracy of neural networks in brain wave diagnosis of schizophrenia
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Encapsulation theory and applications.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
NewMind AI Weekly Chronicles - August'25-Week II
Tartificialntelligence_presentation.pptx
Spectroscopy.pptx food analysis technology
Assigned Numbers - 2025 - Bluetooth® Document
Spectral efficient network and resource selection model in 5G networks
SOPHOS-XG Firewall Administrator PPT.pptx
Encapsulation_ Review paper, used for researhc scholars

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