Java tricky collections interview questions
Question 1 :
What is difference between
List<?> and List<Object> in Java?
Answer :
- List<?>
is List of unknown type while List<Object> is essentially List of
any Type.
- You
can assign List<String>, List<Integer> to List<?> but
you can not assign List<String> to List<Object>.
- This
is because List<Object> can store any any thing including String,
Integer etc but List<String> can only store Strings.
- Some
examples :
Question 2 :
Can you pass
List<String> to a method which accepts List<Object> ?
Answer :
- In
first glance it looks like : String is Object
so List<String> can be used where List<Object> is required but
this is not true.
- It
will result in compilation error.
- This
is because List<Object> can store any any thing including String,
Integer etc but List<String> can only store Strings !!.
Question 3 :
What is Bounded and
Unbounded wildcards in Generics ?
Answer :
- Bounded
wildcards are :
- <?
extends T> which impose an upper bound by ensuring that type must be
sub class of T.
- <?
super T> where its imposing lower bound by ensuring Type must be super
class of T.
- <?>
represent and unbounded type because <?> can be replace with any
Type.
Questions 4 :
What is difference between
List<? extends T> and List <? super T> ?
Answer :
- This
question is related to bounded and unbounded wildcards in Generics.
- Bounded
wildcard : List<? extends T> will accept any List with Type
extending T.
- And
Unbounded wildcard : List<? super T> will accept any List
with type super class of T.
- Example List<? extends Number> can accept List<Integer> or List<Float>.
Question 5 :
How HashMap works in Java ?
Answer :
- HashMap
stores key-value pair in Map & Map.Entry is static nested
class implementation.
- HashMap
works on hashing algorithm and uses hashCode() and equals() method in put
and get methods.
When we call put method by passing key-value
pair :
- HashMap
uses Key hashCode() with hashing to find out the index to store the
key-value pair.
- The
Map.Entry is stored in the LinkedList, so if there are already existing
entry, it uses equals() method to check if the passed key already exists.
- If
entry already exists then it overwrites the value else it creates a new
entry and store this key-value Entry.
When we call get method by passing Key :
- Again
it uses the hashCode() to find the index in the array and then use
equals() method to find the correct Entry and return it’s value.
Remember :
- hashCode()
is used to narrow down the results for fast searching.
- objects
having same hashCode() doesn't mean that they're same, It only means that
those objects are stored in same bucket.
Question 6 :
What are advantages of
using Generics ?
Answer : Generics provides compile time
type-safety and ensures that you only insert correct Type in collection and
avoids ClassCastException during runtime.
Question 7 :
What do you understand by
iterator fail-fast property?
Answer :
- Fail-fast
Iterators fail as soon as they realized that structure of Collection has
been changed since iteration has begun. ( Structural changes means
adding, removing or updating any element from collection while one thread
is Iterating over that collection ).
- Fail-fast
behavior is implemented by keeping a modification count and if iteration
thread realizes the change in modification count it throws
ConcurrentModificationException.
Question 8 :
What is difference between
fail-fast and fail-safe?
Answer :
- You
have understood fail-fast in previous question.
- Fail-safe
iterators are just opposite to fail-fast.
- They
never fail if you modify the underlying collection on which they are iterating,
because they work on clone of Collection instead of original
collection and that’s why they are called as fail-safe iterator.
- Iterator
of CopyOnWriteArrayList is an example of fail-safe Iterator also iterator
written by ConcurrentHashMap keySet is also fail-safe iterator and never
throw ConcurrentModificationException.
Question 9 :
How to avoid
ConcurrentModificationException while iterating a collection?
Answer :
- You
should first try to find another alternative iterator which are fail-safe.
- For
example if you are using List and you can use ListIterator.
- If
it is legacy collection, you can use enumeration.
If above options are not possible then you can
use one of three changes:
- If
you are using JDK1.5 or higher then you can use ConcurrentHashMap and
CopyOnWriteArrayList classes. It is the recommended approach.
- You
can convert the list to an array and then iterate on the array.
- You
can lock the list while iterating by putting it in a synchronized block.
Note that last two
approaches will cause a performance hit.
Question 10 :
Can we use any class as
Map key?
Answer :
We can use any class as Map Key, however
following points should be considered before using them.
- If
the class overrides equals() method, it should also override hashCode()
method.
- The
class should follow the rules associated with equals() and hashCode() for
all instances.
- If
a class field is not used in equals(), you should not use it in hashCode()
method.
- Best
practice for user defined key class is to make it immutable, so that hashCode()
value can be cached for fast performance.
- Also
immutable classes make sure that hashCode() and equals() will not change
in future that will solve any issue with mutability.
For example, let’s say
I have a class MyKey that I am using for HashMap key.
//MyKey name argument passed is used for
equals() and hashCode()
MyKey key =
new MyKey("Pankaj"); //assume hashCode=1234
myHashMap.put(key, "Value");
// Below code will change the key hashCode() and equals()
// but it's location is not changed.
key.setName("Amit"); //assume new hashCode=7890
//below will return null, because HashMap will try to look for key
//in the same index as it was stored but since key is mutated,
//there will be no match and it will return null.
myHashMap.get(new MyKey("Pankaj"));
myHashMap.put(key, "Value");
// Below code will change the key hashCode() and equals()
// but it's location is not changed.
key.setName("Amit"); //assume new hashCode=7890
//below will return null, because HashMap will try to look for key
//in the same index as it was stored but since key is mutated,
//there will be no match and it will return null.
myHashMap.get(new MyKey("Pankaj"));
This is the
reason why String and Integer are mostly used as HashMap keys.
Question 11 :
What are the differences
between Queue and Stack in java?
Answer:
- A
collection designed for holding elements prior to processing.
- Besides
basic Collection operations, queues provide additional insertion,
extraction, and inspection operations.
- Queues
typically, but do not necessarily, order elements in a FIFO
(first-in-first-out) manner.
- Stack
is also a form of Queue but one difference, it is LIFO
(last-in-first-out).
- Whatever
the ordering used, the head of the queue is that element which would be
removed by a call to remove() or poll(). Also note that Stack and Vector
are both synchronized.
Usage:
- Use
a queue if you want to process a stream of incoming items in the order
that they are received.Good for work lists and handling requests.
- Use
a stack if you want to push and pop from the top of the stack only. Good
for recursive algorithms.
Question 12 : How can we make Hashmap
synchronized?
Answer :
HashMap can be synchronized by Map m =
Collections.synchronizedMap(hashMap);
Question 13 : What are IdentityHashMap
and WeakHashMap?
Answer :
IdentityHashMap :
- IdentityHashMap
is similar to HashMap except that it uses reference equality when
comparing elements.
- IdentityHashMap
class is not a widely used Map implementation.
- While
this class implements the Map interface, it intentionally violates Map’s
general contract, which mandates the use of the equals() method when
comparing objects.
- IdentityHashMap
is designed for use only in the rare cases wherein reference-equality
semantics are required.
WeakHashMap :
- WeakHashMap
is an implementation of the Map interface that stores only weak references
to its keys.
- Storing
only weak references allows a key-value pair to be garbage collected when
its key is no longer referenced outside of the WeakHashMap.
- This
class is intended primarily for use with key objects whose equals methods
test for object identity using the == operator.
- Once
such a key is discarded it can never be recreated, so it is impossible to
do a look-up of that key in a WeakHashMap at some later time and be
surprised that its entry has been removed.
Question 14 : How to make a collection
read only?
Answer : Use following methods:
- Collections.unmodifiableList(list);
- Collections.unmodifiableSet(set);
- Collections.unmodifiableMap(map);
These methods takes collection parameter and
return a new read-only collection with same elements as in original collection.
Question 15 : What is NavigableMap in
Java ? What are its benefits over Map?
Answer :
- NavigableMap
Map was added in Java 1.6, it adds navigation capability to Map data
structure.
- It
provides methods like lowerKey() to get keys which is less than specified key,
floorKey() to return keys which is less than or equal to specified key,
ceilingKey() to get keys which is greater than or equal to specified key
and higherKey() to return keys which is greater specified key from a Map.
- It
also provide similar methods to get entries e.g. lowerEntry(),
floorEntry(), ceilingEntry() and higherEntry().
- Apart
from navigation methods, it also provides utilities to create sub-Map e.g.
creating a Map from entries of an exsiting Map like tailMap, headMap and
subMap. headMap() method returns a NavigableMap whose keys are less than
specified, tailMap() returns a NavigableMap whose keys are greater than
the specified and subMap() gives a NavigableMap between a range, specified
by toKey to fromKey.
Question 16 : Which collection classes
provide random access of it’s elements?
Answer : ArrayList, HashMap, TreeMap, Hashtable
classes provide random access to it’s elements.
Question 17 : What is BlockingQueue?
Answer :
- A
Queue 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.
- BlockingQueue
methods come in four forms: one throws an exception, the second returns a
special value (either null or false, depending on the operation), the
third blocks the current thread indefinitely until the operation can
succeed, and the fourth blocks for only a given maximum time limit before
giving up.
Question 18 : When do you use
ConcurrentHashMap in Java?
Answer :
- This
is another advanced level collection interview questions in Java which
normally asked to check whether interviewer is familiar with optimization
done on ConcurrentHashMap or not.
- ConcurrentHashMap
is better suited for situation where you have multiple readers and
one Writer or fewer writers since Map gets locked only during write
operation.
- If
you have equal number of reader and writer than ConcurrentHashMap will
perform in line of Hashtable or synchronized HashMap.
Question 19 : Which implementation of the
List interface provides for the fastest insertion of a new element into the
middle of the list?
Answer :
We have three implementation of List
: Vector, ArrayList, LinkedList.
- 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.
Question 20 : What is the Difference
between the Iterator and ListIterator?
Answer :
- Iterator :
Iterator Can Only get Data From forward Direction .
- ListIterator : An iterator
for lists that allows one to traverse the list in either direction.modify
the list during iteration, and obtain the iterator’s current position in
the list.
- A
ListIterator has no current element. its cursor position always lies between
the element that would be returned by a call to previous() and the element
that would be returned by a call to next(). In a list of length n, there
are n+1 valid index values, from 0 to n, inclusive.
Question 21 : What is
CopyOnWriteArrayList, how it is different than ArrayList and Vector?
Answer :
- CopyOnWriteArrayList
is new List implementation introduced in Java 1.5 which provides better
concurrent access than Synchronized List.
- Better
concurrency is achieved by Copying ArrayList over each write and replace
with original instead of locking.
- Also
CopyOnWriteArrayList doesn't throw any ConcurrentModification Exception.
- Its
different than ArrayList because its thread-safe and ArrayList is not
thread safe and its different than Vector in terms of Concurrency.
- CopyOnWriteArrayList
provides better Concurrency by reducing contention among readers and
writers.
Question 22 : Difference between Vector
and ArrayList?
Answer :
Vector & ArrayList both classes are
implemented using dynamically resizable arrays, providing fast random access
and fast traversal. ArrayList and Vector class both implement the List
interface.
1) Synchronization - ArrayList is not
thread-safe whereas Vector is thread-safe. In Vector class each method like
add(), get(int i) is surrounded with a synchronized block and thus making
Vector class thread-safe.
2) Data growth - Internally, both the ArrayList
and Vector hold onto their contents using an Array. When an element is inserted
into an ArrayList or a Vector, the object will need to expand its internal
array if it runs out of room. A Vector defaults to doubling the size of its
array, while the ArrayList increases its array size by 50 percent.
Question 23 : How Can I Synchronized
ArrayList Object?
Answer : Yes, we can Synchronized Array list
Object with the help of Collections.synchronizedList(<list
object>);
List list = Collections.synchronizedList(new ArrayList());
Question 24 : Which two method you need
to implement for key Object in HashMap ?
Answer : In order to use any object as Key in
HashMap, it must implements equals and hashcode method in Java. Read How
HashMap works in Java for detailed explanation on how equals and hashcode
method is used to put and get object from HashMap.
Question 25 : What will be the problem
if you don't override hashcode() method ?
Answer : You will not be able to recover
your object from hash Map if that is used as key in HashMap.
Question 26 : What will happen if we put
a key object in a HashMap which is already there ?
Answer : This tricky Java questions is part of
How HashMap works in Java, which is also a popular topic to create confusing
and tricky question in Java. well if you put the same key again than it will
replace the old mapping because HashMap doesn't allow duplicate keys.
Question 27 : What is the difference
between a HashMap and a Hashtable in Java?
Answer :
- Hashtable
is synchronized, whereas HashMap is not.
- This
makes HashMap better for non-threaded applications, as unsynchronized
Objects typically perform better than synchronized ones.
- Hashtable
does not allow null keys or values.
- HashMap
allows one null key and any number of null values.
- 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
could easily swap out the HashMap for a LinkedHashMap.
- This
wouldn’t be as easy if you were using Hashtable.
Question 28 : What is difference between
Iterator and Enumeration?
Answer :
Enumeration :
- Enumeration
doesn't have a remove() method.
- Enumeration
acts as Read-only interface, because it has the methods only to traverse
and fetch the objects
- So
Enumeration is used whenever we want to make Collection objects as
Read-only.
Iterator :
- Iterator
has a remove() method.
- Can
be abstract, final, native, static, or synchronized.
- The
main difference between the two is that Iterator is fail-safe. i.e,
If you are using an iterator to go through a collection you can be
sure of no concurrent modifications in the underlying collection which may
happen in multi-threaded environments.
Question 29 : Why insertion and
deletion in ArrayList is slow compared to LinkedList ?
Answer :
- ArrayList
internally uses and array to store the elements, when that array gets
filled by inserting elements a new array of roughly 1.5 times the size of
the original array is created and all the data of old array is copied to
new array.
- During
deletion, all elements present in the array after the deleted elements
have to be moved one step back to fill the space created by deletion. In
linked list data is stored in nodes that have reference to the previous
node and the next node so adding element is simple as creating the node an
updating the next pointer on the last node and the previous pointer on the
new node.
- Deletion
in linked list is fast because it involves only updating the next pointer
in the node before the deleted node and updating the previous pointer in
the node after the deleted node.
Question 30 : Why are Iterators returned
by ArrayList called Fail Fast ?
Answer :
- Because,
if list is structurally modified at any time after the iterator is
created, in any way except through the iterator's own remove or add
methods, the iterator will throw a ConcurrentModificationException.
- Thus,
in the face of concurrent modification, the iterator fails quickly and
cleanly, rather than risking arbitrary, non-deterministic behavior at an
undetermined time in the future.
Question 31 : How do you decide when to
use ArrayList and When to use LinkedList?
Answer :
- If
you need to support random access, without inserting or removing elements
from any place other than the end, then ArrayList offers the optimal
collection.
- If,
however, you need to frequently add and remove elements from the middle of
the list and only access the list elements sequentially, then LinkedList
offers the better implementation.
Question 32 : What is the Properties
class?
Answer : 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.
Question 33 : How to convert a string
array to arraylist?
Answer : new ArrayList(Arrays.asList(myArray));
Question 34 : How can you suppress
unchecked warning in Java ?
Answer :
- javac
compiler for Java 5 generates unchecked warnings if you use combine raw
types and generics types.
- You
can be suppress those warnings by using @SuppressWarnings("unchecked")
annotation.
Question 35 : What is difference between
List<Object> and raw type List in Java?
Answer :
- Main
difference between raw type and parametrized type List<Object> is
that :
- Compiler
will not check type-safety of raw type at compile time but it will
do that for parametrized type and by using Object as Type it inform
compiler that it can hold any Type of Object.
And second difference between them is that you can pass any parametrized type to raw type List but you can not pass List<String> to any method which accept List<Object> it will result in compilation error.
Comments
Post a Comment