You are on page 1of 24

Java Collections Framework contains most commonly asked Java interview questions.

A good understanding of Collections framework is required to understand and leverage many powerful features of Java technology. Here are few important practical questions which can be asked in a Core Java interview.
1. What is Java Collections API? Java Collections framework AP is a unified

architecture for representing and manipulating collections. !he AP contains nterfaces" mplementations # Algorithm to help $ava programmer in everyday programming. n nutshell" this AP does % things at high level
o o o o o

&educes programming efforts. ' ncreases program speed and quality. Allows interoperability among unrelated AP s. &educes effort to learn and to use new AP s. &educes effort to design new AP s. (ncourages # Fosters software reuse.

!o be specific" !here are si) collection $ava interfaces. !he most basic interface is Collection. !hree interfaces e)tend Collection* +et" ,ist" and +orted+et. !he other two collection interfaces" -ap and +orted-ap" do not e)tend Collection" as they represent mappings rather than true collections. .. What is an Iterator?+ome of the collection classes provide traversal of their contents via a $ava.util. terator interface. !his interface allows you to walk through a collection of ob$ects" operating on each ob$ect in turn. &emember when using terators that they contain a snapshot of the collection at the time the terator was obtained/ generally it is not advisable to modify the collection itself while traversing an terator. 0. What is the difference between java.util.Iterator and java.util.ListIterator? terator * (nables you to traverse through a collection in the forward direction only" for obtaining or removing elements ,ist terator * e)tends terator" and allows bidirectional traversal of list and also allows the modification of elements.

1. What is HashMap and Map? -ap is nterface which is part of Java collections framework. !his is to store 2ey 3alue pair" and Hashmap is class that implements that using hashing technique.
5.

ifference between HashMap and Hash!able? Co"pare Hashtable vs HashMap?4oth Hashtable # Hash-ap provide key'value access to data. !he Hashtable is one of the original collection classes in Java 5also called as legacy classes6. Hash-ap is part of the new Collections Framework" added with Java ." v7... !here are several differences between Hash-ap and Hashtable in Java as listed below
o

!he Hash-ap class is roughly equivalent to Hashtable" e)cept that it is unsynchroni8ed and permits nulls. 5Hash-ap allows null values as key and value whereas Hashtable doesn9t allow nulls6.

Hash-ap does not guarantee that the order of the map will remain constant over time. 4ut one of Hash-ap:s subclasses is ,inkedHash-ap" so in the event that you:d want predictable iteration order 5which is insertion order by default6" you can easily swap out the Hash-ap for a ,inkedHash-ap. !his wouldn:t be as easy if you were using Hashtable.

o o

Hash-ap is non synchroni8ed whereas Hashtable is synchroni8ed. terator in the Hash-ap is fail'fast while the enumerator for the Hashtable isn:t. +o this could be a design consideration.

%. What does s#nchroni$ed "eans in Hashtable conte%t?+ynchroni8ed means only one thread can modify a hash table at one point of time. Any thread before performing an update on a hashtable will have to acquire a lock on the ob$ect while others will wait for lock to be released. ;. What is fail&fast propert#?At high level ' Fail'fast is a property of a system or software with respect to its response to failures. A fail'fast system is designed to immediately report any failure or condition that is likely to lead to failure. Fail'fast systems are usually designed to stop normal operation rather than attempt to continue a possibly'flawed process.

<hen a problem occurs" a fail'fast system fails immediately and visibly. Failing fast is a non'intuitive technique* =failing immediately and visibly= sounds like it would make your software more fragile" but it actually makes it more robust. 4ugs are easier to find and fi)" so fewer go into production. n Java" Fail'fast term can be related to conte)t of iterators. f an iterator has been created on a collection ob$ect and some other thread tries to modify the collection ob$ect =structurally=" a concurrent modification e)ception will be thrown. t 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" = llegalArgument()ception= will be thrown.
8. Wh# doesn't Collection e%tend Cloneable and (eriali$able? From +un FA>

Page* -any Collection implementations 5including all of the ones provided by the J?26 will have a public clone method" but it would be mistake to require it of all Collections. For e)ample" what does it mean to clone a Collection that:s backed by a terabyte +>, database@ +hould the method call cause the company to requisition a new disk farm@ +imilar arguments hold for seriali8able. f the client doesn:t know the actual type of a Collection" it:s much more fle)ible and less error prone to have the client decide what type of Collection is desired" create an empty Collection of this type" and use the addAll method to copy the elements of the original collection into the new one. Aote on +ome mportant !erms
o

+ynchroni8ed means only one thread can modify a hash table at one point of time. 4asically" it means that any thread before performing an update on a hashtable will have to acquire a lock on the ob$ect while others will wait for lock to be released.

Fail'fast is relevant from the conte)t of iterators. f an iterator has been created on a collection ob$ect and some other thread tries to modify the collection ob$ect =structurallyB" a concurrent modification e)ception will be thrown. t is possible for other threads though to invoke =set= method since it doesn9t modify the collection =structurallyB. However" if prior to calling =set=" the collection has been modified structurally" = llegalArgument()ception= will be thrown.

C. How can we "a)e Hash"ap s#nchroni$ed? Hash-ap can be synchroni8ed by Map m = Collections.synchronizedMap(hashMap);
7D. Where will #ou use Hashtable and where will #ou use HashMap? !here are

multiple aspects to this decision* 7. !he basic difference between a Hashtable and an Hash-ap is that" Hashtable is synchroni8ed while Hash-ap is not. !hus whenever there is a possibility of multiple threads accessing the same instance" one should use Hashtable. <hile if not multiple threads are going to access the

same instance then use Hash-ap. Aon synchroni8ed data structure will give
better performance than the synchroni8ed one. .. f there is a possibility in future that ' there can be a scenario when you may require to retain the order of ob$ects in the Collection with key'value pair then Hash-ap can be a good choice. As one of Hash-ap:s subclasses is ,inkedHash-ap" so in the event that you:d want predictable iteration order 5which is insertion order by default6" you can easily swap out the Hash-ap for a ,inkedHash-ap. !his wouldn:t be as easy if you were using Hashtable. Also if you have multiple thread accessing you Hash-ap then Collections.synchroni8ed-ap56 method can be leveraged. Everall Hash-ap gives you more fle)ibility in terms of possible future changes.
11.

ifference between *ector and Arra#List? What is the *ector class? 3ector # Array,ist both classes are implemented using dynamically resi8able arrays" providing fast random access and fast traversal. Array,ist and 3ector class both implement the ,ist interface. 4oth the classes are member of Java collection framework" therefore from an AP perspective" these two classes are very similar. However" there are still some ma$or differences between the two. 4elow are some key differences
o

3ector is a legacy class which has been retrofitted to implement the ,ist interface since Java . platform v7..

3ector is synchroni8ed whereas Array,ist is not. (ven though 3ector class is synchroni8ed" still when you want programs to run in multithreading environment using Array,ist with Collections.synchroni8ed,ist56 is recommended over 3ector.

Array,ist has no default si8e while vector has a default si8e of 7D.

!he (numerations returned by 3ector:s elements method are not fail'fast. <hereas Arraay,ist does not have any method returning (numerations.

12. What is the

ifference between +nu"eration and Iterator interface?

(numeration and terator are the interface available in $ava.util package. !he functionality of (numeration interface is duplicated by the terator interface. Aew implementations should consider using terator in preference to (numeration. terators differ from enumerations in following ways*
1.

(numeration contains . methods namely has-ore(lements56 # ne)t(lement56 whereas terator contains three methods namely hasAe)t56" ne)t56"remove56.

2.

terator adds an optional remove operation" and has shorter method names. Fsing remove56 we can delete the ob$ects but (numeration interface does not support this feature.

3.

(numeration interface is used by legacy classes. 3ector.elements56 # Hashtable.elements56 method returns (numeration. terator is returned by all Java Collections Framework classes. $ava.util.Collection.iterator56 method returns an instance of terator.

.. Wh# Java *ector class is considered obsolete or unofficiall# deprecated? or Wh# should I alwa#s use Arra#List over *ector?Gou should use Array,ist over 3ector because you should default to non'synchroni8ed access. 3ector synchroni8es each individual method. !hat:s almost never what you want to do. Henerally you want to synchroni8e a whole sequence of operations. +ynchroni8ing individual operations is both less safe 5if you iterate over a 3ector" for instance" you still need to take out a lock to avoid anyone else changing the collection at the same time6 but also slower 5why take out a lock repeatedly when once will be enough6@ Ef course" it also has the overhead of locking even when you don:t need to. t:s a very flawed approach to have synchroni8ed access as default. Gou can always decorate a collection using Collections.synchroni8ed,ist ' the fact that 3ector

combines both the =resi8ed array= collection implementation with the =synchroni8e every operation= bit is another e)ample of poor design/ the decoration approach gives cleaner separation of concerns. 3ector also has a few legacy methods around enumeration and element retrieval which are different than the ,ist interface" and developers 5especially those who learned Java before 7..6 can tend to use them if they are in the code. Although (numerations are faster" they don:t check if the collection was modified during iteration" which can cause issues" and given that 3ector might be chosen for its syncroni8ation ' with the attendant access from multiple threads" this makes it a particularly pernicious problem. Fsage of these methods also couples a lot of code to 3ector" such that it won:t be easy to replace it with a different ,ist implementation. ?espite all above reasons +un may never officially deprecate 3ector class. 5&ead details ?eprecate Hashtable and 3ector6 0. What is an enu"eration?An enumeration is an interface containing methods for accessing the underlying data structure from which the enumeration is obtained. t is a construct which collection classes return when you request a collection of all the ob$ects stored in the collection. t allows sequential access to all the elements stored in the collection. 1. What is the difference between +nu"eration and Iterator? !he functionality of (numeration interface is duplicated by the terator interface. terator has a remove56 method while (numeration doesn:t. (numeration acts as &ead'only interface" because it has the methods only to traverse and fetch the ob$ects" where as using terator we can manipulate the ob$ects also like adding and removing the ob$ects. +o (numeration is used when ever we want to make Collection ob$ects as &ead'only. I. Where will #ou use *ector and where will #ou use Arra#List? !he basic difference between a 3ector and an Array,ist is that" vector is synchroni8ed while Array,ist is not. !hus whenever there is a possibility of multiple threads accessing the same instance" one should use 3ector. <hile if not multiple

threads are going to access the same instance then use Array,ist. Aon synchroni8ed data structure will give better performance than the synchroni8ed one. %. What is the i"portance of hashCode,- and e.uals,- "ethods? How the# are used in Java?!he $ava.lang.Eb$ect has two methods defined in it. !hey are ' public boolean equals5Eb$ect ob$6 public int hashCode56. !hese two methods are used heavily when ob$ects are stored in collections. !here is a contract between these two methods which should be kept in mind while overriding any of these methods. !he Java AP documentation describes it in detail. !he hashCode56 method returns a hash code value for the ob$ect. !his method is supported for the benefit of hashtables such as those provided by $ava.util.Hashtable or $ava.util.Hash-ap. !he general contract of hashCode is* <henever it is invoked on the same ob$ect more than once during an e)ecution of a Java application" the hashCode method must consistently return the same integer" provided no information used in equals comparisons on the ob$ect is modified. !his integer need not remain consistent from one e)ecution of an application to another e)ecution of the same application. f two ob$ects are equal according to the equals5Eb$ect6 method" then calling the hashCode method on each of the two ob$ects must produce the same integer result. t is not required that if two ob$ects are unequal according to the equals5$ava.lang.Eb$ect6 method" then calling the hashCode method on each of the two ob$ects must produce distinct integer results. However" the programmer should be aware that producing distinct integer results for unequal ob$ects may improve the performance of hashtables. As much as is reasonably practical" the hashCode method defined by class Eb$ect does return distinct integers for distinct ob$ects. !he equals5Eb$ect ob$6 method indicates whether some other ob$ect is =equal to= this one. !he equals method implements an equivalence relation on non'null ob$ect references*

t is refle)ive* for any non'null reference value )" ).equals5)6 should return true. t is symmetric* for any non'null reference values ) and y" ).equals5y6 should return true if and only if y.equals5)6 returns true. t is transitive* for any non'null reference values )" y" and 8" if ).equals5y6 returns true and y.equals586 returns true" then ).equals586 should return true. t is consistent* for any non'null reference values ) and y" multiple invocations of ).equals5y6 consistently return true or consistently return false" provided no information used in equals comparisons on the ob$ects is modified. For any non' null reference value )" ).equals5null6 should return false. !he equals method for class Eb$ect implements the most discriminating possible equivalence relation on ob$ects/ that is" for any non'null reference values ) and y" this method returns true if and only if ) and y refer to the same ob$ect 5) JJ y has the value true6. Aote that it is generally necessary to override the hashCode method whenever this method is overridden" so as to maintain the general contract for the hashCode method" which states that equal ob$ects must have equal hash codes. A practical +%a"ple of hashcode,- / e.uals,-0 !his can be applied to classes that need to be stored in +et collections. +ets use equals56 to enforce non' duplicates" and Hash+et uses hashCode56 as a first'cut test for equality. !echnically hashCode56 isn:t necessary then since equals56 will always be used in the end" but providing a meaningful hashCode56 will improve performance for very large sets or ob$ects that take a long time to compare using equals56. ;. What is the difference between (ortin1 perfor"ance of Arra#s.sort,- vs Collections.sort,- ? Which one is faster? Which one to use and when? -any developers are concerned about the performance difference between $ava.util.Array.sort56 $ava.util.Collections.sort56 methods. 4oth methods have same algorithm the only difference is type of input to them. Collections.sort56 has a input as ,ist so it does a translation of ,ist to array and vice versa which is an additional step while sorting. +o this should be used when you are trying to sort a

list. Arrays.sort is for arrays so the sorting is done directly on the array. +o clearly it should be used when you have a array available with you and you want to sort it. K. What is java.util.concurrent 2loc)in13ueue? How it can be used? Java has implementation of 4locking>ueue available since Java 7.I. 4locking >ueue interface e)tends collection interface" which provides you power of collections inside a queue. 4locking >ueue is a type of >ueue that additionally supports operations that wait for the queue to become non'empty when retrieving an element" and wait for space to become available in the queue when storing an element. A typical usage e)ample would be based on a producer'consumer scenario. Aote that a 4locking>ueue can safely be used with multiple producers and multiple consumers. An Array4locking>ueue is a implementation of blocking queue with an array used to store the queued ob$ects. !he head of the queue is that element that has been on the queue the longest time. !he tail of the queue is that element that has been on the queue the shortest time. Aew elements are inserted at the tail of the queue" and the queue retrieval operations obtain elements at the head of the queue. Array4locking>ueue requires you to specify the capacity of queue at the ob$ect construction time itself. Ence created" the capacity cannot be increased. !his is a classic =bounded buffer= 5fi)ed si8e buffer6" in which a fi)ed'si8ed array holds elements inserted by producers and e)tracted by consumers. Attempts to put an element to a full queue will result in the put operation blocking/ attempts to retrieve an element from an empty queue will be blocked. C. (et / List interface e%tend Collection4 so Wh# doesn't Map interface e%tend Collection?!hough the -ap interface is part of collections framework" it does not e)tend collection interface. !his is by design" and the answer to this questions is best described in +un:s FA> Page* !his was by design. <e feel that mappings are not collections and collections are not mappings. !hus" it makes little sense for -ap to e)tend the Collection interface 5or vice versa6. f a -ap is a Collection" what are the elements@ !he only reasonable answer is =2ey'value pairs=" but this provides a very limited 5and not particularly useful6 -ap abstraction. Gou can:t ask what value a given key maps to" nor can you delete

the entry for a given key without knowing what value it maps to. Collection could be made to e)tend -ap" but this raises the question* what are the keys@ !here:s no really satisfactory answer" and forcing one leads to an unnatural interface. -aps can be viewed as Collections 5of keys" values" or pairs6" and this fact is reflected in the three =Collection view operations= on -aps 5key+et" entry+et" and values6. <hile it is" in principle" possible to view a ,ist as a -ap mapping indices to elements" this has the nasty property that deleting an element from the ,ist changes the 2ey associated with every element before the deleted element. !hat:s why we don:t have a map view operation on ,ists. 7D. Which i"ple"entation of the List interface provides for the fastest insertion of a new ele"ent into the "iddle of the list? a. 3ector b. Array,ist c. ,inked,ist Array,ist and 3ector both use an array to store the elements of the list. <hen 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. !he ,inked,ist is implemented using a doubly linked list/ an insertion requires only the updating of the links at the point of insertion. !herefore" the ,inked,ist allows for fast insertions and deletions.
11. What is the difference between Arra#List and Lin)edList? ,Arra#List vs

Lin)edList.- $ava.util.Array,ist and $ava.util.,inked,ist are two Collections classes used for storing lists of ob$ect references Here are so"e )e# differences0
o

Array,ist uses primitive ob$ect array for storing ob$ects whereas ,inked,ist is made up of a chain of nodes. (ach node stores an element and the pointer to the ne)t node. A singly linked list only has pointers to ne)t. A doubly linked list has a pointer to the ne)t and the previous element. !his makes walking the list backward easier.

Array,ist implements the &andomAccess interface" and ,inked,ist does not. !he commonly used Array,ist implementation uses primitive Eb$ect array for internal storage. !herefore an Array,ist is much faster than a ,inked,ist for random access" that is" when accessing arbitrary list elements using the get method. Aote that the get method is implemented

for ,inked,ists" but it requires a sequential scan from the front or back of the list. !his scan is very slow. For a ,inked,ist" there:s no fast way to access the Ath element of the list.
o

Adding and deleting at the start and middle of the Array,ist is slow" because all the later elements have to be copied forward or backward. 5Fsing +ystem.arrayCopy566 <hereas ,inked lists are faster for inserts and deletes anywhere in the list" since all you do is update a few ne)t and previous pointers of a node.

(ach element of a linked list 5especially a doubly linked list6 uses a bit more memory than its equivalent in array list" due to the need for ne)t and previous pointers.

Array,ist may also have a performance issue when the internal array fills up. !he array,ist has to create a new array and copy all the elements there. !he Array,ist has a growth algorithm of 5nL06M.N7" meaning that each time the buffer is too small it will create a new one of si8e 5nL06M.N7 where n is the number of elements of the current buffer. Hence if we can guess the number of elements that we are going to have" then it makes sense to create a arraylist with that capacity during ob$ect creation 5using construtor new Array,ist5capacity66. <hereas ,inked,ists should not have such capacity issues.

70. Where will #ou use Arra#List and Where will #ou use Lin)edList? 5r Which one to use when ,Arra#List 6 Lin)edList-.4elow is a snippet from +FA:s site. !he Java +?2 contains . implementations of the ,ist interface ' Array,ist and ,inked,ist. f you frequently add elements to the beginning of the ,ist or iterate over the ,ist to delete elements from its interior" you should consider using ,inked,ist. !hese operations require constant'time in a ,inked,ist and linear' time in an Array,ist. 4ut you pay a big price in performance. Positional access requires linear'time in a ,inked,ist and constant'time in an Array,ist. 71. What is perfor"ance of various Java collection i"ple"entations6al1orith"s? What is 2i1 '5' notation for each of the" ?

(ach $ava collection implementation class have different performance for different methods" which makes them suitable for different programming needs.
o

Perfor"ance of Map interface i"ple"entations Hashtable An instance of Hashtable has two parameters that affect its performance* initial capacity and load factor. !he capacity is the number of buckets in the hash table" and the initial capacity is simply the capacity at the time the hash table is created. Aote that the hash table is open* in the case of a =hash collision=" a single bucket stores multiple entries" which must be searched sequentially. !he load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. !he initial capacity and load factor parameters are merely hints to the implementation. !he e)act details as to when and whether the rehash method is invoked are implementation'dependent. HashMap !his implementation provides constant'time O 4ig E Aotation is E576 P performance for the basic operations 5get and put6" assuming the hash function disperses the elements properly among the buckets. teration over collection views requires time proportional to the =capacity= of the Hash-ap instance 5the number of buckets6 plus its si8e 5the number of key'value mappings6. !hus" it:s very important not to set the initial capacity too high 5or the load factor too low6 if iteration performance is important. !reeMap !he !ree-ap implementation provides guaranteed log5n6 O 4ig E Aotation is E5log A6 P time cost for the contains2ey" get" put and remove operations. Lin)edHashMap

A linked hash map has two parameters that affect its performance* initial capacity and load factor. !hey are defined precisely as for Hash-ap. Aote" however" that the penalty for choosing an e)cessively high value for initial capacity is less severe for this class than for Hash-ap" as iteration times for this class are unaffected by capacity.
o

Perfor"ance of (et interface i"ple"entations Hash(et !he Hash+et class offers constant'time O 4ig E Aotation is E576 P performance for the basic operations 5add" remove" contains and si8e6" assuming the hash function disperses the elements properly among the buckets. terating over this set requires time proportional to the sum of the Hash+et instance:s si8e 5the number of elements6 plus the =capacity= of the backing Hash-ap instance 5the number of buckets6. !hus" it:s very important not to set the initial capacity too high 5or the load factor too low6 if iteration performance is important. !ree(et !he !ree+et implementation provides guaranteed log5n6 time cost for the basic operations 5add" remove and contains6. Lin)edHash(et A linked hash set has two parameters that affect its performance* initial capacity and load factor. !hey are defined precisely as for Hash+et. Aote" however" that the penalty for choosing an e)cessively high value for initial capacity is less severe for this class than for Hash+et" as iteration times for this class are unaffected by capacity.

Perfor"ance of List interface i"ple"entations Lin)edList

' Performance of get and remove methods is linear time O 4ig E Aotation is E5n6 P ' Performance of add and terator.remove methods is constant' time O 4ig E Aotation is E576 P Arra#List ' !he si8e" is(mpty" get" set" iterator" and list terator operations run in constant time. O 4ig E Aotation is E576 P ' !he add operation runs in amorti8ed constant time O 4ig E Aotation is E576 P " but in worst case 5since the array must be resi8ed and copied6 adding n elements requires linear time O 4ig E Aotation is E5n6 P ' Performance of remove method is linear time O 4ig E Aotation is E5n6 P ' All of the other operations run in linear time O 4ig E Aotation is E5n6 P. !he constant factor is low compared to that for the ,inked,ist implementation. Can you think of a questions which is not part of this post@ Please don:t forget to share it with me in comments section # will try to include it in the list. 7ou "a# also li)e

89 J 2C 3uestions / Answers for Java Connectivit# 8: Multi&!hreadin1 3uestions for Java

evelopers & Java evelopers

atabase

9; Interview 3uestions / Answers for Hadoop developers

7ou "i1ht also li)e0 Java 4asics >uestions .1 nterview >uestions # Answers for Hadoop developers 7. J?4C >uestions # Answers for Java ?evelopers ' Java ?atabase Connectivity Java Harbage Collection >uestions 7D -ulti'!hreading >uestions for Java ?evelopers Lin)Within

think you should also include the new $ava.util.concurrent questions in it. !his is a good collection" but $ava I has a more powerful set of collections like Array4locking>ueue etc. -ay 77" .DDC 77*DC A-

I!(urfer said... !hanksQQ this is a great collection. have bookmarked it in delicious. June .1" .DDC I*1I P-

I3JA*A said... Aice collection +eptember %" .DDC 7D*7; A-

1uest said... good collection +eptember .0" .DDC 7D*IK A-

Anon#"ous said... !hanks for putting in all the effort to create this entry. Ectober .%" .DDC C*.; A-

Anon#"ous said... ()cellent. useful and sensible collation ?ecember 0" .DDC %*01 P-

nahrun1ser1<n$un1 said...

Collection tells you what collections are" and how they:ll make your $ob easier and your programs better. Gou:ll learn about the core elements that comprise the Collections Framework* interfaces" implementations and algorithms. ?ecember ;" .DDC %*DC A-

(A=JA7 7A A* said... good questions collection. ?ecember 7D" .DDC I*II A-

hiraj (in1h said... nice collection...keep it upQQQ ?ecember 7;" .DDC 0*.. A-

Anon#"ous said... A question was asked recently was what is the difference between an Array,ist and a ,inked,ist. ?ecember .%" .DDC 7D*77 P-

(oftware Wi)ipedia said... RAnonymous * !hanks for your comment. have not included this in my list of questions here. ' ?ifference between Array,ist and ,inked,ist. ' <here to use Array,ist or ,inked,ist. January 1" .D7D I*1; P-

Anon#"ous said...

Hreat collection. very useful. ,akshmanan 3enkatachalam -arch .1" .D7D ;*D0 P-

"oorth# said... it is really good. however" if you provide real world e)amples on equals and hashCode" then it would be perfect. April ;" .D7D 7D*0I A-

(oftware Wi)ipedia said... Rmoorthy ' !hanks for your comment. have updated the post with an e)ample for hashCodeMequals. Hope this helps. ,et me know if you have any other questionsMsuggestions. April .;" .D7D 7.*70 P-

Anon#"ous said... Hood Collection..2eep up the good work and do keep posting more of this.. -ay 71" .D7D 77*7C A-

Anon#"ous said... take e)ception to a lot of these points. For e)ample there:s almost no e)cuse to ever use a 3ector" Hashtable or (numeration. !hey should be considered deprecated. 3ector and Hashtable:s synchroni8ation is flawed 5eg fine grained only" open to ?o+6 and their performance is poor 5eg they have inefficient growth algorithms6. !he only e)cuse for using them is when interfacing with legacy AP s that require them. +tating that 3ector should be used in multithreaded code over Array,ist makes me cringe. Also" while what you say about Array,ist vs ,inked,ist is true" but often an

Array,ist still wins out over ,inked,ist. ,inked,ist puts more strain on the heap" the garbage collector" and it has little spatial locality so tends to result in more cache misses. -y general rule of thumb is that if you:d be better off with a ,inked,ist" benchmark it. Gou:ll probably be surprised. -ay 7C" .D7D K*07 A-

Anon#"ous said... ;. iterators do fail'fast. !hey aren:t fail'save. -ay 7C" .D7D C*.0 A-

(oftware Wi)ipedia said... RAnonymous ' !hanks for pointing out. am going to correct it. Also this gives room for few more interesting questions which can be added. -ay 7C" .D7D 77*.C A-

(oftware Wi)ipedia said... RAnonymous ' !hanks again. have now updated this post with fail'fast. had to read several places to understand what fail'fast means. hope now the S; has correct answerMquestion. am going to do more reading on =difference between fail'fast vs fail'safe= and try to update it in this post when have some good information with me. Please feel free to share any informationMresources you have. -ay 7C" .D7D 0*.K P-

(oftware Wi)ipedia said... RAnonymous ' Fpdated the 3ector vs Array,ist section after doing more reading on it.

Also compiled a new question about why 3ector should be considered a deprecated class. Hope this improves the Array,istM3ector part. still need to do more reading on <hy HashtableM(numeration should not be used. <ill be back with updates soon. -ay 7C" .D7D 1*0. P-

Prasanth Jalasutra" said... nice questions. !hanks Prashant http*MMprasanthabout$ava.blogspot.comM -ay .7" .D7D ;*1; A-

("o1>9 said... 3ery few of items are interesting... -ay .7" .D7D K*7; A-

Anon#"ous said... Hood Collection....but e)pected copyonwrite collections qns as well...+ee my blog for ConcurrentHash-ap 3s Hashmap 3s hashtable !hanks" Apurv -y Java 4log* http*MMapurvagnihotri.blogspot.comM June 7I" .D7D 7D*I0 A-

?ro" said... RApurva ' !hanks for feedback. will try to add that too. June 7I" .D7D 1*D0 P-

@achna said... its really helpful for me for my infosys interview. Pradeepmala http*MMpradeepmala.blogspot.comM July .." .D7D 7D*IC P-

@achna said... hi its really work for my infosys interview... Pradeepmala http*MMpradeepmala.blogspot.comM July .." .D7D 77*DD P-

(achin said... RPradeepmala ' am really glad to see your comment. !his makes me really happy that this collection is proving helpful for real interviews. Feel free to provide any suggestions on missing questions in this list. !hanks again for your comment. July .%" .D7D 7.*1I P-

ritu said... realy very good collection "realy very helpfull August 7%" .D7D K*IK A-

Aaushal A. (har"a said... >uite impressive collection on Collections +eptember .7" .D7D 0*7; A-

Anon#"ous said... &eally great collection....very nice Ectober 71" .D7D 1*DI A-

Anon#"ous said... 3ery good collection. 4ut :d like to see more questions on the big o comple)ity wrt collections especially in regards to hashtable and hashmap. <hat if the value for a specific key is list@ How does big o effect etc. !hanks again" Fsha Ectober .%" .D7D 7D*0K P-

(achin said... RFsha ' !hanks for your comment. have now added a new question at the end covering the performance and 4ig E notation aspect. Hope this helps. would like to get more details on the specific question you have about a =key is list=. ,et me know. Ectober .;" .D7D %*D7 P-

Job interview !echni.ues said... Gou have provided such a great information. !hese questions are always asked in an interview. Gou have a huge collection of questions. really appreciate sharing this great post. 2eep up your work.. Ectober 0D" .D7D 7.*0K A-

Anon#"ous said... !his is really a nice post and really helpful. ?ecember 77" .D7D 7D*DC A-

Anon#"ous said... god bless you mateQ this is very useful for people entering the real Java world. ?ecember 7%" .D7D 7D*7K P-

(elva"4 (iva1an1ai said... En I6 ?ifference between Hash-ap and Hash!able@ Compare Hashtable vs Hash-ap@ you say Hash-ap is fail'fast" isn:t it fail'safe@ because during iteration it creates a separate copy of the ob$ects and if there was a modification to the ob$ects during iteration it doesn:t halt 5fail'fast6. ?ecember 7%" .D7D 77*.I P-

(achin said... R+elvam ' !hanks for commenting. !he Fail'fast vs Fail'safe is a tricky one. 7. !he iterator of Hash-ap will throw Concurrent-odification()ception when the ob$ect is =+tructurally= modified 5e)cept through the iterator:s own remove or add methods6. &efer the Java AP doc here OHash-ap AP ?ocP .. Also check out this link to get a sample code which can demonstrate the difference O Fail'fast vs Fail'safe find this link really useful and referred it several times. Hope you find it useful. ?ecember 7;" .D7D 7D*1; A-

javarevisited said...

!hanks for this nice article. have similar blog post ?ifference between Hash-ap and Hash!able@ Can we make hashmap synchroni8ed which complements this topic hope that would be useful . !hanks Javin F T Protocol nterview >uestions February .." .D77 ;*1D A-

brijesh said... good collection -arch .." .D77 K*70 A-

brijesh said... !he iterator of Hash-ap will throw Concurrent-odification()ception when the ob$ect is =+tructurally= modified 5e)cept through the iterator:s own remove or add methods6. &efer the Java AP doc here -arch .." .D77 K*71 A-

Javin Paul said... have recently written two articles about my e)perience in Java interview you guys may find it interesting !op .D Core Java nterview question !op 7D Java +eriali8ation nterview >uestion April 7C" .D77 ;*.1 A-

Ainshu) Chandra said... 3ery nice collections of questions. People may also like ' Collections

... which is little detailed. *6 !hanks for sharing such a good =Collection= of questions. -ay 71" .D77 .*D7 P-

Javin Paul said... !he functionality of (numeration interface is duplicated by the terator interface. terator has a remove56 method while (numeration doesn:t. (numeration acts as &ead'only interface" because it has the methods only to traverse and fetch the ob$ects" where as using terator we can manipulate the ob$ects also like adding and removing the ob$ects. have also blogged about tdifference between iterator and enumeration here. June 77" .D77 7*I0 A-

sudharsan said... Hood 2nowledge >uestions June .7" .D77 %*1D A-

Bda#Prasad said... Aice collections it helped me for nterview R 4ank of (ngland.hashcode and equals needs more view of the real code snippets.could be provided here

You might also like