Java util.collections is one of the most important package in java and the important of this package can be understand by C++/C developer where they need to performance lots of code for managing pointers and collections and this all work is abstracted by Java and this is one of most important factor for java being developer friendly. Generally questions asked in this package are related to which class is used in what case, which will give best performance, concurrency of collection package etc. 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.
Most of IT units in financial industry do highlights 'Threading Concept' as the crux of Java language but as per current trend it seems interviewers are being more pragmatic that educative.
Writing programs without touching java.util.* seems very uncommon unless we are up to printing 'hello world' :)
Following are some very basic but conceptually very strong features originating from Collection Framework. This article is targeted to provide just a pointer to the areas where we developers need to brush up ourselves before our interviews. I am not (as of now) listing answers here as they could be easily find out on web.
- What is hashing in Java?
- Why does one need to consider overriding hashcode() & equals() for keys used in HashMap? Is it mandatory to override these methods to allow the object getting used as keys? What will happen if we do not implement them?
- Wrapper (Immutable) classes (Integer, String etc) are considered as right candidates for HashMap keys. Why?
- When get() is invoked on a HashMap(), what are the steps followed by Java to get the associated value back?
- What is the underlying data structure used by HashMap to store its value?
- What is the underlying data structure for ConcurrentHashMap? How does it differ from HashMap and HashTable?
- Java memory model has been revised and tuned with 'Tiger' version of java 5. What are the associated updates?
- How Java 5 overcomes infamous 'Double-Checked Locking' paradigm?
- What happens when a map has to be resized to accommodate more items? What will happen if another thread calls get() when resizing is underway?
- How is the memory in use gets affected by choosing between ArrayList and LinkedList?
- Can program execution go different by choosing between Enhanced for loop and old fashioned index based loop for a collection?
- Can we iterate over a List and call remove if a certain condition matches? *Interviewer generally tries to understand whether candidate is clear about fast-fail feature, ConcurrentModificationException and use of Iterator.
Did you know
1. Comparator and Comparable though gets referred mostly together but they belong to different java libraries.
2. Java 5 Enums could be used to provide Singleton implementation.
Would appreciate the feedback and if someone is willing to add answers against these queries then most welcome.
These are the most common java collection interview questions -
Java Collections framework API is a unified architecture for representing and manipulating collections. The API contains Interfaces, Implementations and Algorithm to help java programmer in everyday programming. In nutshell, this API does 6 things at high level
- Reduces programming efforts. - Increases program speed and quality.
- Allows interoperability among unrelated apis.
- Reduces effort to learn and to use new apis.
- Reduces effort to design new apis.
- Encourages & Fosters software reuse.
What is an Iterator?
What is the difference between java.util.Iterator and java.util.listiterator?
listiterator : extends Iterator, and allows bidirectional traversal of list and also allows the modification of elements.
What is hashmap and Map?
Difference between hashmap and hashtable? Compare Hashtable vs hashmap?
- 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).
- Hashmap does not guarantee that the order of the map will remain constant over time. But one of hashmap's subclasses is linkedhashmap, so in the event that you'd want predictable iteration order (which is insertion order by default), you can easily swap out the hashmap for a linkedhashmap. This wouldn't be as easy if you were using Hashtable.
- Hashmap is non synchronized whereas Hashtable is synchronized.
- Iterator in the hashmap is fail-fast while the enumerator for the Hashtable isn't. So this could be a design consideration.
What is fail-fast property?
When 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. Bugs are easier to find and fix, so fewer go into production.
In Java, Fail-fast term can be related to 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.
Why doesn't Collection extend Cloneable and Serializable?
- 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.
- Fail-fast 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.
Where will you use Hashtable and where will you use hashmap?
Difference between Vector and arraylist? What is the Vector class?
- Vector is a legacy class which has been retrofitted to implement the List interface since Java 2 platform v1.2
- Vector is synchronized whereas arraylist is not. Even though Vector class is synchronized, still when you want programs to run in multithreading environment using arraylist with Collections.synchronizedlist() is recommended over Vector.
- Arraylist has no default size while vector has a default size of 10.
- The Enumerations returned by Vector's elements method are not fail-fast. Whereas arraaylist does not have any method returning Enumerations.
Enumeration and Iterator are the interface available in java.util package. The functionality of Enumeration interface is duplicated by the Iterator interface. New implementations should consider using Iterator in preference to Enumeration. Iterators differ from enumerations in following ways:
Why Java Vector class is considered obsolete or unofficially deprecated? Or Why should I always use arraylist over Vector?
Of course, it also has the overhead of locking even when you don't need to. It's a very flawed approach to have synchronized access as default. You can always decorate a collection using Collections.synchronizedlist - the fact that Vector combines both the "resized array" collection implementation with the "synchronize every operation" bit is another example of poor design; the decoration approach gives cleaner separation of concerns.
What is an enumeration?
Where will you use Vector and where will you use arraylist?
What is the importance of hashcode() and equals() methods? How they are used in Java?
There is a contract between these two methods which should be kept in mind while overriding any of these methods.
The Java API documentation describes it in detail. The hashcode() method returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable or java.util.hashmap. The general contract of hashcode is:
Whenever it is invoked on the same object more than once during an execution of a Java application, the hashcode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application. If two objects are equal according to the equals(Object) method, then calling the hashcode method on each of the two objects must produce the same integer result. It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashcode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables. As much as is reasonably practical, the hashcode method defined by class Object does return distinct integers for distinct objects. The equals(Object obj) method indicates whether some other object is "equal to" this one. The equals method implements an equivalence relation on non-null object references:
It is symmetric: for any non-null 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 non-null 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 non-null 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 objects is modified. For any non-null reference value x, x.equals(null) should return false. The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).
Note 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 objects must have equal hash codes.
A practical Example of hashcode() & equals(): This can be applied to classes that need to be stored in Set collections. Sets use equals() to enforce non-duplicates, and hashset uses hashcode() as a first-cut test for equality. Technically hashcode() isn't necessary then since equals() will always be used in the end, but providing a meaningful hashcode() will improve performance for very large sets or objects that take a long time to compare using equals().
What is the difference between Sorting performance of Arrays.sort() vs Collections.sort() ? Which one is faster? Which one to use and when?
What is java.util.concurrent blockingqueue? How it can be used?
Set & List interface extend Collection, so Why doesn't Map interface extend Collection?
Which implementation of the List interface provides for the fastest insertion of a new element into the middle of the list?
Iteration over collection views requires time proportional to the "capacity" of the hashmap instance (the number of buckets) plus its size (the number of key-value mappings). Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.
- The add operation runs in amortized constant time [ Big O Notation is O(1) ] , but in worst case (since the array must be resized and copied) adding n elements requires linear time [ Big O Notation is O(n) ]
- Performance of remove method is linear time [ Big O Notation is O(n) ]
- All of the other operations run in linear time [ Big O Notation is O(n) ]. The constant factor is low compared to that for the linkedlist implementation.