Friday, July 27, 2012

Difference Between HashMap and HashTable



This question oftenly asked in interview to check whether candidate understand correct usage of collection classes and aware of alternative solutions available.

1. The HashMap class is roughly equivalent to Hashtable, except that it is non synchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn't allow nulls).
2. HashMap does not guarantee that the order of the map will remain constant over time.
3. HashMap is non synchronized whereas Hashtable is synchronized.
4. Iterator in the HashMap is  fail-fast  while the enumerator for the Hashtable is not and throw ConcurrentModificationException if any other Thread modifies the map structurally  by adding or removing any element except Iterator's own remove()  method. But this is not a guaranteed behavior and will be done by JVM on best effort.

Note on Some Important Terms

1)Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.

2)Fail-safe is relevant from the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally", a concurrent modification exception wjavascript:void(0)ill be thrown. It is possible for other threads though to invoke "set" method since it doesn't modify the collection "structurally". However, if prior to calling "set", the collection has been modified structurally, "IllegalArgumentException" will be thrown.

3)Structurally modification means deleting or inserting element which could effectively change the structure of map.

HashMap can be synchronized by

Map m = Collections.synchronizeMap(hashMap);

Hope this will be useful.Please provide your valuable feed back for us! Thank you for visiting here !

What are differences between Enumeration and Iterator


What are differences between Enumeration and Iterator  This question is from early ages of interview , I have not seen this question on recent interviews but it was common during 2006-2007 , now days questions like implementation of HashMap, ConcurrentHashMap etc has take its place, nonetheless its very useful

to know fundamental difference between Iterator and EnumerationSome time its also asked as  Iterator vs Enumeration or Enumeration vs Iterator which is same. important point to note is that both Iterator and Enumeration provides way to traverse or navigate through entire collection in java

Between Enumeration and Iterator, Enumeration is older and its there from JDK1.0 while iterator was introduced later. Iterator can be used with Java arraylist,  java hashmap keyset  and with any other collection classes.


difference between iterator and enumeration in javaAnother similarity between Iterator and Enumeration in Java is that  functionality of Enumeration interface is duplicated by the Iterator interface.

Only major difference between Enumeration and iterator is Iterator has a remove() method while Enumeration doesn't. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, where as by using Iterator we can manipulate the objects like adding and removing the objects from collection e.g. Arraylist.

Also Iterator is more secure and safe as compared to Enumeration because it  does not allow other thread to modify the collection object while some thread is iterating over it and throws ConcurrentModificationException. This is by far most important fact for me for deciding between Iterator vs Enumeration in Java.

In Summary both Enumeration and Iterator will give successive elements, but Iterator is new and improved version where method names are shorter, and has new method called remove. Here is a short comparison:

Enumeration
hasMoreElement()
nextElement()
N/A


Iterator
hasNext()
next()
remove()

So Enumeration is used when ever we want to make Collection objects as Read-only.

Saturday, July 14, 2012

Java Collections Interview Questions

                   Java Collections Interview Questions

What is HashMap and Map?
Map is Interface and Hashmap is class that implements this interface.

What is the significance of ListIterator?
Or
What is the difference b/w Iterator and ListIterator?
Iterator : Enables you to cycle through a collection in the forward direction only, for obtaining or removing elements
ListIterator : It extends Iterator, allow bidirectional traversal of list and the modification of elements
Difference between HashMap and HashTable? Can we make hashmap synchronized?
1. The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn’t allow nulls).
2. HashMap does not guarantee that the order of the map will remain constant over time.
3. HashMap is non synchronized whereas Hashtable is synchronized.
4. Iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't.
Note on Some Important Terms
1)Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.
2)Fail-safe is relevant from the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally”, a concurrent modification exception will be thrown. It is possible for other threads though to invoke "set" method since it doesn’t modify the collection "structurally”. However, if prior to calling "set", the collection has been modified structurally, "IllegalArgumentException" will be thrown.
HashMap can be synchronized by
Map m = Collections.synchronizeMap(hashMap);

What is the difference between set and list?
A Set stores elements in an unordered way and does not contain duplicate elements, whereas a list stores elements in an ordered way but may contain duplicate elements.

Difference between Vector and ArrayList? What is the Vector class?
Vector is synchronized whereas ArrayList is not. The Vector class provides the capability to implement a growable array of objects. ArrayList and Vector class both implement the List interface. Both classes are implemented using dynamically resizable arrays, providing fast random access and fast traversal. In vector the data is retrieved using the elementAt() method while in ArrayList, it is done using the get() method. ArrayList has no default size while vector has a default size of 10. when you want programs to run in multithreading environment then use concept of vector because it is synchronized. But ArrayList is not synchronized so, avoid use of it in a multithreading environment.

What is an Iterator interface? Is Iterator a Class or Interface? What is its use?
The Iterator is an interface, used to traverse through the elements of a Collection. It is not advisable to modify the collection itself while traversing an Iterator.

What is the Collections API?
The Collections API is a set of classes and interfaces that support operations on collections of objects.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.

What is the List interface?
The List interface provides support for ordered collections of objects.

How can we access elements of a collection?
We can access the elements of a collection using the following ways:
1.Every collection object has get(index) method to get the element of the object. This method will return Object.
2.Collection provide Enumeration or Iterator object so that we can get the objects of a collection one by one.

What is the Set interface?
The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements.

What’s the difference between a queue and a stack?
Stack is a data structure that is based on last-in-first-out rule (LIFO), while queues are based on First-in-first-out (FIFO) rule.

What is the Map interface?
The Map interface is used associate keys with values.

What is the Properties class?
The properties class is a subclass of Hashtable that can be read from or written to a stream. It also provides the capability to specify a set of default values to be used. 

Which implementation of the List interface provides for the fastest insertion of a new element into the middle of the list?
a. Vector
b. ArrayList
c. LinkedList
d. None of the above
ArrayList and Vector both use an array to store the elements of the list. When an element is inserted into the middle of the list the elements that follow the insertion point must be shifted to make room for the new element. The LinkedList is implemented using a doubly linked list; an insertion requires only the updating of the links at the point of insertion. Therefore, the LinkedList allows for fast insertions and deletions.

How can we use hashset in collection interface?
This class implements the set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the Null element.
This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets.

What are differences between Enumeration, ArrayList, Hashtable and Collections and Collection?
Enumeration: It is series of elements. It can be use to enumerate through the elements of a vector, keys or values of a hashtable. You can not remove elements from Enumeration.
ArrayList: It is re-sizable array implementation. Belongs to 'List' group in collection. It permits all elements, including null. It is not thread -safe.
Hashtable: It maps key to value. You can use non-null value for key or value. It is part of group Map in collection.
Collections: It implements Polymorphic algorithms which operate on collections.
Collection: It is the root interface in the collection hierarchy.

What is difference between array & arraylist?
An ArrayList is resizable, where as, an array is not. ArrayList is a part of the Collection Framework. We can store any type of objects, and we can deal with only objects. It is growable. Array is collection of similar data items. We can have array of primitives or objects. It is of fixed size. We can have multi dimensional arrays.
Array: can store primitive            ArrayList: Stores object only
Array: fix size                            ArrayList: resizable
Array: can have multi dimensional
Array: lang                                ArrayList: Collection framework

Can you limit the initial capacity of vector in java?
Yes you can limit the initial capacity. We can construct an empty vector with specified initial capacity
public vector(int initialcapacity)

What method should the key class of Hashmap override?
The methods to override are equals() and hashCode().

What is the difference between Enumeration and Iterator?
The functionality of Enumeration interface is duplicated by the Iterator interface. Iterator has a remove() method while Enumeration doesn't. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, where as using Iterator we can manipulate the objects also like adding and removing the objects.
So Enumeration is used when ever we want to make Collection objects as Read-only.