All posts by ratneshjavarnd

Differences between HashMap and Hashtable ?

diffhasmaphashtable

HashMap

1) The underlyingdata structure is Hashtable.
2) Duplicate keys are not allowed but values can be duplicated.
3) Insertion order is not preserved and it is based on hash code of the keys.
4) Heterogeneous objects are allowed for both key and value.
5) Null is allowed for keys(only once) and for values(any number).

Entry interface

• Each key-value pair is called one entry without existing Map objectthere is no chance of existing entry object hence interface entry is define inside Mapinterface(inner interface).
Example:
interface Map
{
……………..;
……………..;
……………..;
interface Entry
{
Object getKey();
Object getValue(); on Entry we can apply these 3 methods.
Object setValue(Object new);
}
}

Map

1) If we want to represent a group of objects as “key-value” pair then we should go for Map interface.
2) Both key and value are objects only.
3) Duplicate keys are not allowed but values can be duplicated
4) Each key-value pair is called “one entry”.
Continue reading Map

Comparison of Set implemented class objects

setcomparable

Comparison of Comparable and Comparator ?

compconparable

Comparable vs Comparator

• For predefined Comparable classes default natural sorting order is already available if we are not satisfied with default natural sorting order then we can define our own customized sorting order by Comparator.
• For predefined non Comparableclasses [like StringBuffer] default natural sorting order is not available we can define our own sorting order by using Comparator object.
Continue reading Comparable vs Comparator

Comparator Interface

• Comparator interface present in java.util package this interface defines the following 2 methods.
1) public int compare(Object obj1,Object Obj2);
comparatorinterface
2) public booleanequals(Objectobj);
• Whenever we are implementing Comparator interface we have to provide implementation only for compare() method.
• Implementing equals() method is optional because it is already available from Object class through inheritance.

Comparable interface

• Comparable interface present in java.lang package and contains only one method compareTo() method.
public int compareTo(Object obj);
Example:
obj1.compareTo(obj2);
Diagram:
comparableinterface
Continue reading Comparable interface

TreeSet

1) The underlying data structure is balanced tree.
2) Duplicate objects are not allowed.
3) Insertion order is not preserved and it is based on some sorting order of objects.
4) Heterogeneous objects are not allowed if we are trying to insert heterogeneous objects then we will get ClassCastException.
5) Null insertion is possible(only once).
Continue reading TreeSet