In this session you will learn:
Objects
Collections
Garbage Collection
For more information, visit this link: https://www.mindsmapped.com/courses/software-development/online-java-training-for-beginners/
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
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