What
are differences between HashMap vs IdentityHashMap in java?
Property
java.util.HashMap
java.util.IdentityHashMap
1
Keys comparison object-equality
vs reference-equality
HashMap when
comparing keys (and values) performs object-equality not reference-equality.
In an HashMap, two keys k1 and k2 are equal if and only if (k1==null ?
k2==null : k1.equals(k2))
IdentityHashMap when
comparing keys (and values) performs reference-equality in place of
object-equality. In an IdentityHashMap, two keys k1 and k2 are equal if and
only if (k1==k2)
2
Initial size
Constructs a new HashMap, Its initial
capacity is 16 in java.
new HashMap();
|
Constructs a new IdentityHashMap, with
maximum size of 21 in java.
new
IdentityHashMap();
|
3
Introduced in which java
version
HashMap was introduced
in second version of java i.e. JDK 2.0
IdentityHashMap was
introduced in fourth version of java i.e. JDK 4.0
4
Program
Program 1 shows >
comparing keys (and values) performs object-equality in place of reference-equality . In an HashMap, two keys k1 and k2 are equal if and only if (k1==null ? k2==null : k1.equals(k2)).
comparing keys (and values) performs object-equality in place of reference-equality . In an HashMap, two keys k1 and k2 are equal if and only if (k1==null ? k2==null : k1.equals(k2)).
Program 2 shows >
comparing keys (and
values) performs reference-equality in place of object-equality. In an
IdentityHashMap, two keys k1 and k2 are equal if and only if (k1==k2).
5
overridden equals() and
hashCode() method call?
As shown in Program 3.
overridden equals() and hashCode()
method are not called when put, get methods are
called in IdentityHashMap.
Because IdentityHashMap
implements equals() and hashCode() method by itself and checks for reference-equality
of keys.
6
Application - can
maintain proxy object
HashMap cannot be used
to maintain proxy object.
IdentityHashMap can be
used to maintain proxy objects. For example, we might need to maintain
proxy object for each object debugged in the program.
What
is WeakHashMap in java?
An entry in a
WeakHashMap will be automatically removed by garbage collector when its key is
no longer in ordinary use. Mapping for a given key will not prevent the key
from being discarded by the garbage collector, (i.e. made finalizable,
finalized, and then reclaimed). When a key has been discarded its entry is
removed from the map in java.
The behavior of
the java.util.WeakHashMap class depends upon garbage collector
The behavior of
the WeakHashMap class depends upon garbage collector in java. Because the
garbage collector may discard keys at any time, in
WeakHashMap it may look like some unknown thread is silently removing entries.
Even if you synchronize WeakHashMap instance and invoke none of
its methods,
·
it is possible for the size method to return smaller values
over time,
·
for isEmpty method to return false and then true,
·
for containsKey method to return true and later false for a
given key,
·
for get method to return a value for a given key but later
return null,
·
for put method to return null, and
·
for remove method to return false for a key that previously
existed in the WeakHashMap.
Each key object in a WeakHashMap is stored indirectly as the
referent of a weak reference. Therefore a key will be removed automatically
only after the weak references to it, both inside and outside of the map, have
been cleared by the garbage collector.
.
What is EnumSet in java?
Answer. Freshers must know about EnumMap in java.
EnumSet all
elements comes from a single enum type that is specified when the set is
created in java.
Order of elements
in EnumSet in java
The
java.util.EnumSet maintains natural order (the order in which the
enum constants are declared) of elements in java.
Iterator on
EnumSet in java
The iterator
returned by the iterator method traverses the elements in their natural
order (the order in which the enum constants are declared).
iterator never
throw ConcurrentModificationException and it may or
may not show the effects of any modifications to the set that occur while the
iteration is in progress.
Null elements in
EnumSet in java
Null elements
are not allowed in EnumSet in java. Attempts to insert a null element will
throw NullPointerException in java.
What
is EnumMap in java?
Answer. Freshers must be able to answer
this collection framework interview question in java. A java.util.EnumMap is specialized Map implementation for use with
enum type keys.
EnumMap all keys
comes from a single enum type that is specified when the set is created in
java.
Order of keys in
EnumMap in java
The EnumMap
maintains natural order (the order in which the enum constants
are declared) of keys in java.
Iterator on
EnumMap in java
The iterator
returned by the iterator method in EnumMap traverses the elements in their natural
order of keys(the order in which the enum constants are declared).
iterator never
throw ConcurrentModificationException and it may or
may not show the effects of any modifications to the map that occur while the
iteration is in progress in java.
Null allowed in
EnumMap in java?
Null keys are
not allowed in EnumMap. Attempts to insert a
null key will throw NullPointerException.
But, Null values
are allowed in EnumMap in java.
Collection
interview Question 23. How to implement own/custom HashMap in java? Or How
HashMap works in java?
I will be
explaining how we will put and get key-value pair in HashMap by
overriding-
>equals
method - helps in checking equality of entry objects.
>hashCode
method - helps in finding bucket’s index on which data
will be stored.
Entry<K,V>
We store key-value pair
by using Entry<K,V>
Entry contains
·
K key,
·
V value and
·
Entry<K,V> next (i.e. next entry on that location of bucket).
static class Entry<K, V> {
K key;
V value;
Entry<K,V> next;
public Entry(K key, V value, Entry<K,V> next){
this.key = key;
this.value = value;
this.next = next;
}
}
|
Initially, we have bucket of capacity=4. (all indexes of bucket i.e.
0,1,2,3 are pointing to null)
We will calculate hash by using our hash(K key) method -
in this case it returns
key/capacity= 21%4= 1.
So, 1 will be the
index of bucket on which newEntry object
will be stored.
We will go to 1st index as it is pointing
to null we will put our newEntry object there
At completion of this step,
our HashMap will look like this-
We will calculate hash
by using our hash(K key) method - in this case it returns
key/capacity= 25%4= 1.
So, 1 will be the index of bucket on which newEntry object will be stored.
We will go to 1st index, it contains entry with key=21, we will compare two
keys(i.e. compare 21 with 25 by using equals
method), as two keys are different we check whether entry with
key=21’s next is null or not, if next is null we will put our
newEntry object on next.
At completion of this
step our HashMap will look like this-
We will calculate hash
by using our hash(K key) method - in this case it returns
key/capacity= 30%4= 2.
So, 2 will be the
index of bucket on which newEntry object will be stored.
We will go to 2nd index as it is pointing
to null we will put our newEntry object there.
At completion of this
step, our HashMap will look like this-
We will calculate hash
by using our hash(K key) method - in this case it returns
key/capacity= 33%4= 1,
So, 1 will be the index of bucket on which newEntry object will be stored.
We will go to 1st index -
>it contains entry
with key=21, we will compare two keys (i.e. compare 21 with 33 by using equals method, as two keys are different,
proceed to next of entry with key=21 (proceed only if next
is not null).
>now, next contains entry
with key=25, we will compare two keys (i.e. compare 25 with 33 by using equals method, as two keys are different,
now next of entry with key=25 is pointing to null so we
won’t proceed further, we will put our newEntry object on next.
At completion of this
step our HashMap will look like this-
What
do you mean by fail-fast and fast-safe? What is
ConcurrentModificationException?
Answer.
Iterator
returned by few Collection framework Classes are fail-fast, means
any structural modification made to these classes during iteration will throw ConcurrentModificationException.
Some important
classes whose returned iterator is fail-fast >
·
ArrayList
·
LinkedList
·
vector
·
HashSet
Iterator
returned by few Collection framework Classes are fail-safe, means any
structural modification made to these classes during iteration won’t throw any
Exception.
Some important
classes whose returned iterator is fail-safe >
·
CopyOnWriteArrayList
·
CopyOnWriteArraySet
·
ConcurrentSkipListSet
What are different ways of iterating over elements in
Set?
Answer. Creating HashSet and add element.
Set<String> hashSet=new
HashSet<String>();
hashSet.add("javaMadeSoEasy");
|
1.
Iterate over elements in HashSet using
iterator()
iterator() method returns
iterator to iterate over elements in HashSet.
Iterator<String>
iterator=hashSet.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
|
iterator returned by HashSet is fail-fast.
2.
Iterate over elements in Set using enumeration
Enumeration<String>
listEnum=Collections.enumeration(set);
while(listEnum.hasMoreElements()){
System.out.println(listEnum.nextElement());
}
|
enumeration is also fail-fast.
3.
Iterate over elements in Set using enhanced
for loop
for
(String string : set) {
System.out.println(string);
}
|
enhanced for loop is also
fail-fast.
What are different ways of iterating over keys, values
and entry in Map?
Answer. Create and put key-value pairs in HashMap >
Map<Integer,String> hashMap=new
HashMap<Integer,String>();
hashMap.put(11, "javaMadeSoEasy");
hashMap.put(21, "bmw");
hashMap.put(31, "ferrari");
|
1.
Iterate over keys -
hashMap.keySet().iterator() method
returns iterator to iterate over keys in HashMap.
Iterator<Integer>
keyIterator=hashMap.keySet().iterator();
while(keyIterator.hasNext()){
System.out.println(keyIterator.next());
}
/*OUTPUT
21
11
31
*/
|
2.
Iterate over values -
hashMap.values().iterator() method
returns iterator to iterate over keys in HashMap.
Iterator<String>
valueIterator=hashMap.values().iterator();
while(valueIterator.hasNext()){
System.out.println(valueIterator.next());
}
/*OUTPUT
javaMadeSoEasy
audi
ferrari
*/
|
iterator returned is fail-fast..
3.
Iterate over Entry-
hashMap.entrySet().iterator() method
returns iterator to iterate over keys in HashMap.
Iterator<Entry<Integer, String>>
entryIterator=hashMap.entrySet().iterator();
while(entryIterator.hasNext()){
System.out.println(entryIterator.next());
}
/*OUTPUT
21=javaMadeSoEasy
11=audi
31=ferrari
*/
|
iterator returned is fail-fast..
What is difference between Comparable and Comparator? How can you sort List?
Answer.
Property
|
Comparable
|
Comparator
|
|
1
|
Comparing instances of
class
|
Comparable
is used to compare instances of same class
|
Comparator
can be used to compare instances of same or different classes.
|
2
|
sorting
order
|
Comparable can be implemented
by class which need to define a natural ordering for its objects.
Example
- String, Integer, Long , Date and all other wrapper
classes implements Comparable.
|
Comparator
is implemented when one wants a different sorting order and define
custom way of comparing two instances.
|
3
|
Changes to class
|
For using Comparable, original Class must
implement it.
Example-
class Employee implements
Comparable<Employee>
For using Comparable, Employee Class must implement it, no other
class can implement it.
|
Class itself can implement Comparator
or
any other class can implement Comparator.
Hence avoiding modification to original class.
Example-
class
ComparatorName implements
Comparator<Employee>
class
ComparatorId implements
Comparator<Employee>
In above example modifications were made to
ComparatorName and ComparatorId.
Hence avoiding modification to Employee class.
|
4
|
Sorting on basis on one
or many criteria
|
Provides sorting only on
one criteria, because Comparable can be implemented by original
class only.
|
We
can use Comparator to sort class on many criterias because class
itself or any other class can implement Comparator.
|
5
|
Method
|
compareTo method
@Override
public int
compareTo(Employee obj) {
//sort Employee on basis of
name(ascending order)
return this.name.compareTo(obj.name);
}
Method compares this with obj object and returns a
integer.
·
positive – this is greater than
obj
·
zero – this is equal to obj
·
negative – this is less than obj
|
compare method
@Override
public int
compare(Employee obj1, Employee obj2) {
//sort Employee on basis of
name(ascending order)
return
obj1.name.compareTo(obj2.name);
}
Method compares obj1 with obj2 object
and returns a integer.
·
positive – obj1 is greater than
obj2
·
zero – obj1 is equal to obj2
·
negative – obj1 is less than obj2
|
6
|
Package
|
java.lang
java.lang package is automatically imported by every program in java.
Hence,
we need to write explicit statement for importing
java.lang.Comparable.
|
java.util
We need to write explicit import statement
-
import
java.util.Comparator
|
7
|
Using Collections.sort
|
Let's say we wanna sort list of Employee,
Collections.sort(list) uses Comparable interface for sorting class.
As used in Program 1
|
Let's say we wanna sort list of Employee,
Collections.sort(list,new
ComparatorName());
uses Comparator interface for sorting
class.
As used in Program 5
|
No comments:
Post a Comment
Note: only a member of this blog may post a comment.