0% found this document useful (0 votes)
135 views33 pages

Struts Extra

The document compares Struts 1 and Struts 2 frameworks. Struts 2 Actions are more flexible than Struts 1 Actions by not requiring inheritance from a base class. Struts 2 also improves testability and makes it easier to harvest input through POJOs and OGNL.

Uploaded by

Neeti Lakhotia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
135 views33 pages

Struts Extra

The document compares Struts 1 and Struts 2 frameworks. Struts 2 Actions are more flexible than Struts 1 Actions by not requiring inheritance from a base class. Struts 2 also improves testability and makes it easier to harvest input through POJOs and OGNL.

Uploaded by

Neeti Lakhotia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 33

Feature Struts 1 Struts 2

An Struts 2 Action may implement


an Action interface, along with other interfaces to
Struts 1 requires Action classes to extend an abstract enable optional and custom services. Struts 2 provides
Action base class. A common problem in Struts 1 is a base ActionSupport class to implement commonly
classes programming to abstract classes instead of used interfaces. Albeit, the Action interface
interfaces. is not required. Any POJO object with
a execute signature can be used as an Struts 2
Action object.

Struts 1 Actions are singletons and must be thread-


Struts 2 Action objects are instantiated for each
safe since there will only be one instance of a class
request, so there are no thread-safety issues. (In
to handle all requests for that Action. The singleton
Threading practice, servlet containers generate many throw-
strategy places restrictions on what can be done with
Model away objects per request, and one more object does
Struts 1 Actions and requires extra care to develop.
not impose a performance penalty or impact garbage
Action resources must be thread-safe or
collection.)
synchronized.

Struts 2 Actions are not coupled to a container. Most


often the servlet contexts are represented as simple
Struts 1 Actions have dependencies on the servlet
Maps, allowing Actions to be tested in isolation. Struts
Servlet API since the HttpServletRequest and
2 Actions can still access the original request and
Dependency HttpServletResponse is passed to
response, if required. However, other architectural
the execute method when an Action is invoked.
elements reduce or eliminate the need to access the
HttpServetRequest or HttpServletResponse directly.

A major hurdle to testing Struts 1 Actions is that Struts 2 Actions can be tested by instantiating the
the execute method exposes the Servlet API. A Action, setting properties, and invoking methods.
Testability
third-party extension, Struts TestCase, offers a set of Dependency Injection support also makes testing
mock object for Struts 1. simpler.

Struts 2 uses Action properties as input properties,


Struts 1 uses an ActionForm object to capture input. eliminating the need for a second input object. Input
Like Actions, all ActionForms must extend a base properties may be rich object types which may have
class. Since other JavaBeans cannot be used as their own properties. The Action properties can be
Harvesting ActionForms, developers often create redundant accessed from the web page via the taglibs. Struts 2
Input classes to capture input. DynaBeans can used as an also supports the ActionForm pattern, as well as POJO
alternative to creating conventional ActionForm form objects and POJO Actions. Rich object types,
classes, but, here too, developers may be including business or domain objects, can be used as
redescribing existing JavaBeans. input/output objects. The ModelDriven feature
simplifies taglb references to POJO input objects.

Struts 1 integrates with JSTL, so it uses the JSTL EL. Struts 2 can use JSTL, but the framework also
Expression The EL has basic object graph traversal, but supports a more powerful and flexible expression
Language relatively weak collection and indexed property language called "Object Graph Notation Language"
support. (OGNL).
Struts 2 uses a "ValueStack" technology so that the
taglibs can access values without coupling your view
Binding
Struts 1 uses the standard JSP mechanism for to the object type it is rendering. The ValueStack
values into
binding objects into the page context for access. strategy allows reuse of views across a range of types
views
which may have the same property name but different
property types.

Struts 1 ActionForm properties are usually all


Struts 2 uses OGNL for type conversion. The
Type Strings. Struts 1 uses Commons-Beanutils for type
framework includes converters for basic and common
Conversion conversion. Converters are per-class, and not
object types and primitives.
configurable per instance.

Struts 2 supports manual validation via


Struts 1 supports manual validation via
the validate method and the XWork Validation
a validate method on the ActionForm, or through
framework. The Xwork Validation Framework supports
Validation an extension to the Commons Validator. Classes can
chaining validation into sub-properties using the
have different validation contexts for the same class,
validations defined for the properties class type and
but cannot chain to validations on sub-objects.
the validation context.

Control Of Struts 1 supports separate Request Processors Struts 2 supports creating different lifecycles on a per
Action (lifecycles) for each module, but all the Actions in the Action basis via Interceptor Stacks. Custom stacks can
Execution module must share the same lifecycle. be created and used with different Actions, as needed.

Difference between SendRedirect and Forward

Now let’s see some difference between these two method of servlet API in tabular format.

Forward() SendRediret()
When we use forward method request is In case of sendRedirect request is transfer to
transfer to other resource within the same another resource to different domain or
server for further processing. different server for futher processing.

In case of forward Web container handle all When you use SendRedirect container
process internally and client or browser is not transfers the request to client or browser so
involved. url given inside the sendRedirect method is
visible as a new request to the client.

When forward is called In case of SendRedirect call old request and


on requestdispather object we pass request response object is lost because it’s treated as
and response object so our old request object new request by the browser.
is present on new resource which is going to
process our request

Visually we are not able to see the forwarded In address bar we are able to see the new
address, its is transparent redirected address it’s not transparent.

Using forward () method is faster then send SendRedirect is slower because one extra
redirect. round trip is required beasue completely new
request is created and old request object is
lost.Two browser request requird.
When we redirect using forward and we want But in sendRedirect if we want to use we have
to use same data in new resource we can use to store the data in session or pass along with
request.setAttribute () as we have request the URL.
object available.

JSP Servlets

JSP is a webpage scripting language that can Servlets are Java programs that are already
generate dynamic content. compiled which also creates dynamic web content.

In MVC, jsp act as a view. In MVC, servlet act as a controller.

It’s easier to code in JSP than in Java Servlets. Its little much code to write here.

JSP are generally preferred when there is not much servlets are best for use when there is more
processing of data required. processing and manipulation involved.

JSP run slower compared to Servlet as it takes Servlets run faster compared to JSP.
compilation time to convert into Java Servlets.

The advantage of JSP programming over servlets is There is no such custom tag facility in servlets.
that we can build custom tags which can directly
call Java beans.

We can achieve functionality of JSP at client side by There are no such methods for servlets.
running JavaScript at client side.

Collection interview Question 1. What is Collection framework in java?


Answer. It’s the basic Collection framework interview question. Freshers must know about this. java.util.Collection is
the root interface in the hierarchy of Java Collection framework in java.
The JDK does not provide any classes which directly implements this interface, but it provides classes which are
implementations of more specific subinterfaces like Set and List in java.
java.util.Set extends java.util.Collection interface in java.
HashSet, CopyOnWriteArraySet, LinkedHashSet, TreeSet, ConcurrentSkipListSet, EnumSet classes implements Set
interface.
java.util.List extends java.util.Collection interface in java.
ArrayList, LinkedList, Vector, CopyOnWriteArrayList classes implements List interface.

Collection interview Question 2. Which interfaces and classes are most frequently used in Collection framework in java?
Answer
Most frequently used interface in Collection framework are >
List, Set and Map.
Most frequently used classes in Collection framework are >
HashSet, LinkedHashSet, TreeSet, ConcurrentSkipListSet classes implements Set interface.

ArrayList, LinkedList, Vector, CopyOnWriteArrayList classes implements List interface.

HashMap, Hashtable, ConcurrentHashMap, LinkedHashMap, TreeMap, ConcurrentSkipListMap classes implements Map


interface.

Collection interview Question 3. What are subinterfaces of Collection interface in java? Is Map interface also a
subinterface of Collection interface in java?
Answer. List and Set are subinterfaces of java.util.Collection in java.

It’s important to note Map interface is a member of the Java Collections Framework, but it does not implement
Collection interface in java.

Collection interview Question 4. What are differences between ArrayList and LinkedList in java?
Answer. This is very important collection framework interview question in java.
Property java.util.ArrayList java.util.LinkedList

1 Structure java.util.ArrayList is index based structure in java. A java.util.LinkedList is a data


structure consisting of a group of
nodes which together represent a
sequence.
node is composed of a data and a
reference (in other words, a link) to
the next node in the sequence in
java.

2 Resizable ArrayList is Resizable-array in java. New node is created for storing new
element in LinkedList in java.

3 Initial capacity java.util.ArrayList is created with initial capacity of 10 in For storing every element node is
java. created in LinkedList, so linkedList’s
initial capacity is 0 in java.

4 Ensuring Capacity/ ArrayList is created with initial capacity of 10. For storing every element node is
resizing. ArrayList’s size is increased by 50% i.e. after resizing it’s created, so linkedList’s initial
size become 15 in java. capacity is 0, it’s size grow with
addition of each and every element
in java.

5 RandomAccess ArrayList implements RandomAccess(Marker interface) LinkedList does not implement


interface to indicate that they support fast random access (i.e. RandomAccess interface in java.
index based access) in java.

6 AbstractList and ArrayList extends AbstractList (abstract class) which LinkedList extends
AbstractSequential provides implementation to List interface to minimize AbstractSequentialList (abstract
List the effort required to implement this interface backed class), AbstractSequentialList
by RandomAccess interface. extends AbstractList.
In LinkedList, data is accessed
sequentially, so for obtaining data at
specific index, iteration is done on
nodes sequentially in java.

7 How get(index) Get method of ArrayList directly gets element on Get method of LinkedList iterates on
method works? specified index. Hence, offering O(1) complexity in java. nodes sequentially to get element on
(Though difference specified index. Hence, offering O(n)
has been discussed complexity in java.
briefly in above 2
points but in this in
point we will figure
difference in
detail.)

8 When to use Use ArrayList when get operations is more frequent Use LinkedList when add and remove
than add and remove operations in java. operations are more frequent than
get operations in java.

For more detail like complexity comparison of method please read : ArrayList vs LinkedList in java

Collection interview Question 5. What are differences between ArrayList and Vector in java?
Answer. Another very important collection framework interview question to differentiate between ArrayList and Vector
in java.

Property java.util.ArrayList java.util.Vector

1 synchroniza java.util.ArrayList is not synchronized (because 2 java.util.Vector is synchronized (because 2


tion threads on same ArrayList object can access it at threads on same Vector object cannot access it
same time). at same time).

I have created program to show consequence of I have created program to show advantage of
using ArrayList in multithreading environment. using Vector in multithreading environment.
In the program we will implement our own In the program we will implement our own
arrayList in java. vector in java.

2 Performanc ArrayList is not synchronized, hence its operations Vector is synchronized, hence its operations are
e are faster as compared to Vector in java. slower as compared to ArrayList in java.

If we are working not working in multithreading


environment jdk recommends us to use ArrayList.

3 Enumeratio Enumeration is fail-fast, means any modification Enumeration is fail-safe, means any modification
n made to ArrayList during iteration using made to Vector during iteration using
Enumeration will throw Enumeration don’t throw any exception in java.
ConcurrentModificationException in java.
4 Introduced ArrayList was introduced in second version of java Vector was introduced in first version of java i.e.
in which i.e. JDK 2.0 JDK 1.0
java version But it was refactored in java 2 i.e. JDK 1.2 to
implement the List interface, hence making it a
member of member of the Java Collections
Framework.

5 Ensuring ArrayList is created with initial capacity of 10. Vector is created with initial capacity of 10.
Capacity/ When its full size is increased by 50% i.e. after Vector’s size is increased by 100% i.e. after
resizing. resizing it’s size become 15 in java. resizing it’s size become 20 in java.

6 Custom
implementa
tion

Read :
Read : ArrayList custom implementation
Vector custom implementation

For more detail like complexity comparison of method please read: ArrayList vs Vector- Similarity and Differences in java

Collection interview Question 6. What are differences between List and Set interface in java?
Answer. Another very very important collection framework interview question to differentiate between List and Set in
java.

Property java.util.List java.util.Set

1 Insertion order java.util.List is ordered collection it Most of the java.util.Set implementation does
maintain insertion order in java. not maintain insertion order.

HashSet does not maintains insertion order in


java.

Thought LinkedHashSet maintains insertion


order in java.

TreeSet is sorted by natural order in java.

2 Duplicate elements List allows to store duplicate elements in Set does not allow to store duplicate elements
java. in java.

3 Null keys List allows to store many null keys in java. Most of the Set implementations allow to add
only one null in java.

TreeSet does not allow to add null in java.

4 Getting element on List implementations provide get method Set implementations does not provide any such
specific index to get element on specific index in java. get method to get element on specified index
in java.
ArrayList, Vector, copyOnWriteArrayList
and LinkedList provides -
get(int index)
Method returns element on specified
index.

Get method directly gets element on


specified index. Hence, offering O(1)
complexity.

5 Implementing ArrayList, LinkedList, Vector, HashSet, CopyOnWriteArraySet,


classes CopyOnWriteArrayList classes implements LinkedHashSet, TreeSet, ConcurrentSkipListSet,
List interface in java. EnumSet classes implements Set interface in
java.

6 listIterator listIterator method returns listIterator to Set does not provide anything like listIterator.
iterate over elements in List in java. It simply return Iterator in java.

listIterator provides additional methods as


compared to iterator like
hasPrevious(), previous(), nextIndex(),
previousIndex(), add(E element), set(E
element)

7 Structure and List are Resizable-array implementation of Set uses Map for their implementation.
resizable the java.util.List interface in java. Hence, structure is map based and resizing
depends on Map implementation.
Example > HashSet internally uses HashMap.

8 Index based As ArrayList uses array for implementation Set is not index based structure at all in java.
structure it is index based structure, hence provides
/RandomAccess random access to elements.
But LinkedList is not indexed based
structure in java.

For more detail read : List vs Set - Similarity and Differences in java

Collection interview Question 7. What are differences between Iterator and ListIterator? in java
Answer. This collection framework interview question is tests your knowledge of iterating over different collection
framework classes in java.

java.util.ListIterator java.util.Iterator

1 hasPrevious() method returns true if this listIterator has more elements when No such method in
traversing the list in the reverse direction. java.util.Iterator.

2 previous() returns previous element in iteration (traversing in backward No such method in


direction). java.util.Iterator.
if the iteration has no previous elements than NoSuchElementException is
thrown.
3 nextIndex() method returns the index of the element that would be returned by No such method in
a subsequent call to next() method. If listIterator is at the end of the list than java.util.Iterator.
method returns size of list.

4 previousIndex() method returns the index of the element that would be returned No such method in
by a subsequent call to previous() method. If listIterator is at the start of the list java.util.Iterator.
than method returns -1.

5 add(E element) No such method in


Method inserts the specified element into the list. java.util.Iterator.
The element is inserted immediately before the element that would be returned
by next (So, subsequent call to next would be unaffected), if any, and after the
element that would be returned by previous (So,subsequent call to previous
would return the new element), if any.
If the list does not contain any element than new element will be the sole
element in the list.

6 set(E element) No such method in


Method replaces the last element returned by next() or previous() method with java.util.Iterator.
the specified element. This call can be made only if neither remove nor add have
been called after the last call to next or previous.
If call to set() method is followed up by any call made to remove() or add()
method after next() or previous() than UnsupportedOperationException is
thrown.

7 All the implementations of List interface like ArrayList, LinkedList, Vector, All Implementation classes of
CopyOnWriteArrayList classes returns listIterator. Collection interface’s
subinterfaces like Set and List
return iterator.

For more detail read : Iterator vs ListIterator - Similarity and Differences in java

Collection interview Question 8. What are differences between Collection and Collections in java?
Answer. This is another very important collection framework interview question.In real projects you must have used
both Collection and Collections but what is the difference between two of them in java?

java.util.Collection is the root interface in the hierarchy of Java Collection framework.


The JDK does not provide any classes which directly implements java.util.Collection interface, but it provides classes
such as ArrayList, LinkedList, vector, HashSet, EnumSet, LinkedHashSet, TreeSet, CopyOnWriteArrayList,
CopyOnWriteArraySet, ConcurrentSkipListSet which implements more specific subinterfaces like Set and List in java.

java.util.Collections is a utility class which consists of static methods that operate on or return Collection in java.

java.util.Collections provides method like >


reverse method for reversing List in java.
shuffle method for shuffling elements of List in java.
unmodifiableCollection, unmodifiableSet, unmodifiableList, unmodifiableMap methods for making List, Set and Map
unmodifiable in java.
min method to return smallest element in Collection in java.
max method to return smallest element in Collection.
sort method for sorting List.
synchronizedCollection, synchronizedSet, synchronizedList, synchronizedMap methods for synchronizing List, Set and
Map respectively in java.

Additionally you must know that java.util.Collection and java.util.Collections both were introduced in second version of
java i.e. in JDK 2.0.

Collection interview Question 9. What are core classes and interfaces in java.util.List hierarchy in java?
Answer. Freshers must know core classes in List hierarchy but experienced developers must be able to explain this
java.util.List hierarchy in detail.

java.util.List interface extends java.util.Collection interface.

java.util.ArrayList, java.util.LinkedList, java.util.Vector, java.util.concurrent.CopyOnWriteArrayList classes implements


java.util.List interface.

Also some abstract classes like java.util.AbstractCollection, java.util.AbstractList and java.util.AbstractSequentialList have
been mentioned in hierarchy.

Collection interview Question 10. What are core classes and interfaces in java.util.Set hierarchy?
Answer. Freshers must know core classes in Set hierarchy but experienced developers must be able to explain this
java.util.Set hierarchy in detail.
java.util.Set interface extends java.util.Collection interface.

java.util.HashSet, java.util.concurrent.CopyOnWriteArraySet, java.util.LinkedHashSet, java.util.TreeSet,


java.util.concurrent.ConcurrentSkipListSet, java.util.EnumSet classes implements java.util.Set interface.

Also some abstract classes like java.util.Dictionary and java.util.AbstractSet and java.util.AbstractCollection have been
mentioned in hierarchy.

Collection interview Question 11. What are core classes and interfaces in java.util.Map hierarchy?
Answer. Freshers must know core classes in Map hierarchy but experienced developers must be able to explain this
java.util.Map hierarchy in detail.

java.util.Map interface extends java.util.Collection interface.


java.util.HashMap, java.util.Hashtable, java.util.concurrent.ConcurrentHashMap, java.util.LinkedHashMap,
java.util.TreeMap, java.util.concurrent.ConcurrentSkipListMap, java.util.IdentityHashMap, java.util.WeakHashMap,
java.util.EnumMap classes implements java.util.Map interface.

Also some abstract classes like java.util.Dictionary and java.util.AbstractMap have been mentioned in hierarchy.

Collection interview Question 12. What are differences between Iterator and Enumeration in java?
Answer. Experienced developers must be well versed to answer this collection framework interview question in java.

Differences between java.util.Iterator and java.util.Enumeration in java >


Property java.util.Enumeration java.util.Iterator

1 Remove elements java.util.Enumeration doesn’t allows to java.util.Iterator allows to remove elements from
during iteration remove elements from collection during collection during iteration by using remove()
iteration in java. method in java.

2 Improved naming nextElement() nextElement() has been changed to next() in


conventions in Method Returns the next element of this Iterator.
Iterator enumeration if this enumeration object
has at least one more element to And
provide.
hasMoreElements() has been changed to hasNext()
hasMoreElements() in Iterator.
returns true if enumeration contains
more elements.
3 Introduced in Enumeration was introduced in first Iterator was introduced in second version
which java version of java i.e. JDK 2.0
version of java i.e. JDK 1.0
Iterator was introduced to replace Enumeration in
the Java Collections Framework.
4 Recommendation Java docs recommends iterator over Java docs recommends iterator over enumeration.
enumeration.
5 Enumeration and Enumeration returned by Vector is fail-safe, Iterator returned by Vector are fail-fast, means any
Iterator over Vector means any modification made to Vector structural modification made to ArrayList during
during iteration using Enumeration don’t iteration will throw
throw any exception in java. ConcurrentModificationException in java.

For more detail read : Iterator vs Enumeration - Differences and similarities in java

Collection interview Question 13. How do we override equals and hashcode method in java, write a code to use
Employee as key in HashMap in java? (Important)
Answer. This is one of the most important collection framework interview question in java. Prepare for this question
properly. Freshers must know the concept how to override equals and hashcode method but experienced developers
must be able to write the java code to override equals and hashcode neatly. We will override equals() and hashCode()
like this -

By overriding equals() and hashCode() method we could use custom object as key in HashMap.

1) Check whether obj is null or not.


if(obj==null) //If obj is null, return without comparing obj & Employee class.

2) check whether obj is instance of Employee class or not.


if(this.getClass()!=obj.getClass()) //identifies whether obj is instance of Employee class or not.

3) Then, type cast obj into employee instance.


Employee emp=(Employee)obj; //type cast obj into employee instance.

@Override
public boolean equals(Object obj){

if(obj==null)
return false;

if(this.getClass()!=obj.getClass())
return false;

Employee emp=(Employee)obj;
return (emp.id==this.id || emp.id.equals(this.id))
&& (emp.name==this.name || emp.name.equals(this.name));
}

@Override
public int hashCode(){
int hash=(this.id==null ? 0: this.id.hashCode() ) +
(this.name==null ? 0: this.name.hashCode() );
return hash;
}

Let’s say in an organisation there exists a employee with id=1 and name=’sam’ and some data is stored corresponding
to him, but if modifications have to be made in data, previous data must be overridden.

DETAILED DESCRIPTION : Override equals() and hashCode() method.

Must read : Overriding equals and hashcode method - Top 18 Interview questions in java

Collection interview Question 14. What classes should i prefer to use a key in HashMap in java? (Important)
Answer. This collection framework interview question will check your in depth knowledge of Java’s Collection Api’s. we
should prefer String, Integer, Long, Double, Float, Short and any other wrapper class. Reason behind using them as a key
is that they override equals() and hashCode() method, we need not to write any explicit code for overriding equals() and
hashCode() method in java.
Let’s use Integer class as key in HashMap(Example) -
import java.util.HashMap;
import java.util.Map;
public class StringInMapExample {
public static void main(String...a){

//HashMap's key=Integer class (Integer’s api has already overridden hashCode() and equals() method for us )
Map<Integer, String> hm=new HashMap<Integer, String>();
hm.put(1, "data");
hm.put(1, "data OVERRIDDEN");

System.out.println(hm.get(1));
}
}
/*OUTPUT
data OVERRIDDEN
*/
If, we note above program, what we will see is we didn’t override equals() and hashCode() method, but still we were
able to store data in HashMap, override data and retrieve data using get method.

>Let’s check in Integer’s API, how Integer class has overridden equals() and hashCode() method :
public int hashCode() {
return value;
}
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}

Collection interview Question 15. What are differences between HashMap and Hashtable in java?
Answer. Fresher and Experienced developers must answer this important collection framework interview question in
detail in java.

Differences between java.util.HashMap and java.util.Hashtable in java >


Property java.util.HashMap java.util.Hashtable

1 synchronization java.util.HashMap is not synchronized java.util.Hashtable is synchronized (because 2


(because 2 threads on same HashMap threads on same Hashtable object cannot
object can access it at same time) in java. access it at same time) in java.

2 Performance HashMap is not synchronized, hence its Hashtable is synchronized, hence its
operations are faster as compared to operations are slower as compared to
Hashtable in java. HashMap in java.

If we are working not working in


multithreading environment jdk recommends
us to use HashMap.

3 Null keys and values HashMap allows to store one null key Hashtable does not allow to store null key or
and many null values i.e. many keys can null value.
have null value in java. Any attempt to store null key or value throws
runtimeException (NullPointerException) in
java.

4 Introduced in which HashMap was introduced in second Hashtable was introduced in first version of
java version version of java i.e. JDK 2.0 java i.e. JDK 1.0
But it was refactored in java 2 i.e. JDK 1.2 to
implement the Map interface, hence making it
a member of member of the Java Collections
Framework.

5 Recommendation In non-multithreading environment it is In java 5 i.e. JDK 1.5, it is recommended to use


recommended to use HashMap than ConcurrentHashMap than using Hashtable.
using Hashtable in java.

6 Extends Dictionary HashMap does not extends Dictionary in Hashtable extends Dictionary (which maps
(Abstract class, which is java. non-null keys to values. In a given Dictionary
obsolete) we can look up value corresponding to key) in
java.

For more detail read : HashMap and Hashtable - Similarity and Differences in java

Collection interview Question 16. when to use HashSet vs LinkedHashSet vs TreeSet in java?
Answer. Another very important collection framework interview question to differentiate between following Set
implementations in java.

Differences between java.util.HashSet vs java.util.LinkedHashSet vs java.util.TreeSet in java>


Property java.util.HashSet java.util.LinkedHashSet java.util.TreeSet

1 Insertion order java.util.HashSet does not java.util.LinkedHashSet java.util.TreeSet is sorted by


maintains insertion order maintains insertion order in natural order in java.
in java. java.
Example in java >
Example in java > Example in java > set.add("b");
set.add("b"); set.add("b"); set.add("c");
set.add("c"); set.add("c"); set.add("a");
set.add("a"); set.add("a");
Output >
Output > Output > a
No specific order b b
c c
a

2 Null elements HashSet allows to store LinkedHashSet allows to store TreeSet does not allows to
one null in java. one null in java. store any null in java.

Any attempt to add null throws


runtimeException
(NullPointerException).

3 Data structure For storing elements For storing elements For storing elements TreeSet
internally used for HashSet internally uses LinkedHashSet internally uses internally uses TreeMap.
storing data HashMap. LinkedHashMap.

4 Introduced in java.util.HashSet was java.util.LinkedHashSet was java.util.TreeSet was


which java version introduced in second introduced in second version of introduced in second version of
version of java (1.2) i.e. java (1.4) i.e. JDK 4.0 java (1.2) i.e. JDK 2.0
JDK 2.0
5 Implements which HashSet implements LinkedHashSet implements TreeSet implements
interface java.util.Set interface. java.util.Set interface. java.util.Set
java.util.SortedSet
java.util.NavigableSet
interface.

For more detail read : HashSet vs LinkedHashSet vs TreeSet in java

Collection interview Question 17. What are differences between HashMap and ConcurrentHashMap in java?
Answer. Take my words java developers won’t be able to get away from this very important collection framework
interview question.

Differences between java.util.HashMap and java.util.concurrent.ConcurrentHashMap in java >


Property java.util.HashMap java.util.concurrent. ConcurrentHashMap

synchronization HashMap is not synchronized. ConcurrentHashMap is synchronized.

2 threads on Yes, because HashMap is not synchronized. Yes.


same Map object
can access it at But how despite of being synchronized, 2
concurrently? threads on same ConcurrentHashMap object
can access it at same time?

ConcurrentHashMap is divided into different


segments based on concurrency level. So
different threads can access different segments
concurrently.

Performance We will synchronize HashMap and then compare ConcurrentHashMap’s performance is faster as
its performance with ConcurrentHashMap. compared to HashMap (because it is divided
into segments, as discussed in above point).
We can synchronize hashMap by using
Collections’s class synchronizedMap method. Read this post for performance comparison
between HashMap and ConcurrentHashMap.
Map synchronizedMap =
Collections.synchronizedMap(hashMap);
Now, no 2 threads can access same instance of
map concurrently.
Hence synchronized HashMap’s performance is
slower as compared to ConcurrentHashMap.

But why we didn’t compared HashMap


(unSynchronized) with ConcurrentHashMap?
Because performance of unSynchronized
collection is always better than some
synchronized collection. As, default
(unSynchronized) hashMap didn’t cause any
locking.

Null keys and HashMap allows to store one null key and many ConcurrentHashMap does not allow to store
values null values i.e. any key can have null value. null key or null value.
Any attempt to store null key or value throws
runtimeException (NullPointerException).

iterators The iterators returned by the iterator() method iterators are fail-safe.
of HashMap are fail-fast >
hashMap.keySet().iterator() concurrentHashMap.keySet().iterator()
hashMap.values().iterator() concurrentHashMap.values().iterator()
hashMap.entrySet().iterator() concurrentHashMap.entrySet().iterator()

all three iterators are fail-fast all three iterators are fail-safe.

putIfAbsent HashMap does not contain putIfAbsent method. If map does not contain specified key, put
putIfAbsent method is equivalent to writing specified key-value pair in map and return null.
following code > If map already contains specified key, return
value corresponding to specified key.
synchronized (map){
if (!map.containsKey(key))
return map.put(key, value);
else
Program to use ConcurrentHashMap’s
return map.get(key);
putIfAbsent method
}

Program to create method that provides


functionality similar to putIfAbsent method of
ConcurrentHashMap and to be used with
HashMap

Introduced in HashMap was introduced in java 2 i.e. JDK 1.2, ConcurrentHashMap was introduced in java 5
which java i.e. JDK 1.5, since its introduction Hashtable has
version become obsolete, because of concurrency level
its performance is better than Hashtable.

Implements HashMap implements java.util.Map ConcurrentHashMap implements


which interface java.util.Map and
java.util.concurrent.ConcurrentMap

Package HashMap is in java.util package ConcurrentHashMap is in java.util.concurrent


package.
For more detail read : HashMap and ConcurrentHashMap in java

Collection interview Question 18. When to use HashMap vs Hashtable vs LinkedHashMap vs TreeMap in java?
Answer. Another important collection framework interview question
to differentiate between following Map implementations in java.

Differences between java.util.HashMap vs java.util.Hashtable vs java.util.LinkedHashMap vs java.util.TreeMap >


Property HashMap Hashtable LinkedHashMap TreeMap

1 Insertion order HashMap Hashtable does not LinkedHashMap maintains TreeMap is sorted by
does not maintains insertion insertion order in java. natural order of keys in
maintains order in java. java.
insertion
order in java.
2 Performance HashMap is Hashtable is LinkedHashMap must be TreeMap must be used
not synchronized, hence used only when we want to only when we want
synchronized, its operations are maintain insertion order. sorting based on
hence its slower as compared Time and space overhead is natural order.
operations HashMap. there because for Otherwise sorting
are faster as maintaining order it operations cost
compared to If we are working not internally uses Doubly performance.
Hashtable. working in Linked list. (Comparator is called
multithreading for sorting purpose)
environment jdk
recommends us to use
HashMap.

3 Null keys and HashMap Hashtable does not LinkedHashMap allows to TreeMap does not
values allows to allow to store null key store one null key and allow to store null key
store one null or null value. many null values i.e. any but allow many null
key and many Any attempt to store key can have null value in values.
null values i.e. null key or value java. Any attempt to store
many keys throws null key throws
can have null runtimeException runtimeException
value in java. (NullPointerException) (NullPointerException)
in java. in java.

4 Implements which HashMap Hashtable implements LinkedHashMap TreeMap implements


interface implements java.util.Map implements java.util.Map java.util.Map
java.util.Map java.util.SortedMap
java.util.NavigableMap

5 Implementation HashMap use Hashtable use buckets LinkedHashMap uses TreeMap uses Red
uses? buckets doubly linked lists black tree

6 Complexity of put, O(1) O(1) O(1) O(log(n))


get and remove overhead of updating
methods Doubly Linked list for
maintaining order it
internally uses.

7 Extends HashMap Hashtable extends LinkedHashMap doesn’t TreeMap doesn’t


java.util.Dictionary doesn’t Dictionary (which extends Dictionary. extends Dictionary.
(Abstract class, extends maps non-null keys to
which is obsolete) Dictionary. values. In a given
Dictionary we can look
up value
corresponding to key)

8 Introduced in HashMap was Hashtable was LinkedHashMap was TreeMap was


which java introduced in introduced in first introduced in fourth introduced in second
version? second version of java i.e. JDK version of java i.e. JDK 4.0 version of java i.e. JDK
version of 1.0 2.0
java i.e. JDK
2.0 But it was refactored
in java 2 i.e. JDK 1.2 to
implement the Map
interface, hence
making it a member of
member of the Java
Collections
Framework.

For more detail read : HashMap vs Hashtable vs LinkedHashMap vs TreeMap in java

Collection interview Question 19. What are differences between HashMap vs IdentityHashMap in java?
Answer. This is tricky and complex collection framework interview question for experienced developers in java.

Differences between java.util.HashMap and java.util.IdentityHashMap in java >


Property java.util.HashMap java.util.IdentityHashMap

1 Keys HashMap when comparing keys (and values) IdentityHashMap when comparing keys (and
comparison performs object-equality not reference- values) performs reference-equality in place of
object- equality. In an HashMap, two keys k1 and k2 object-equality. In an IdentityHashMap, two keys
equality vs are equal if and only if (k1==null ? k2==null : k1 and k2 are equal if and only if (k1==k2)
reference- k1.equals(k2))
equality

2 Initial size Constructs a new HashMap, Its initial capacity Constructs a new IdentityHashMap, with
is 16 in java. maximum size of 21 in java.
new HashMap(); new IdentityHashMap();

3 Introduced in HashMap was introduced in second version of IdentityHashMap was introduced in fourth version
which java java i.e. JDK 2.0 of java i.e. JDK 4.0
version

4 Program Program 1 shows > Program 2 shows >


comparing keys (and values) performs object- comparing keys (and values) performs reference-
equality in place of reference-equality . In an equality in place of object-equality. In an
HashMap, two keys k1 and k2 are equal if and IdentityHashMap, two keys k1 and k2 are equal if
only if (k1==null ? k2==null : k1.equals(k2)). and only if (k1==k2).

5 overridden overridden equals() and hashCode() method overridden equals() and hashCode() method are
equals() and are called when put, get methods are called in not called when put, get methods are called in
hashCode() HashMap. IdentityHashMap.
method call? Because IdentityHashMap implements equals()
As shown in Program 3. and hashCode() method by itself and checks for
reference-equality of keys.

As shown in Program 4.

6 Application - HashMap cannot be used to maintain proxy IdentityHashMap can be used to maintain proxy
can maintain object. objects. For example, we might need to maintain
proxy object proxy object for each object debugged in the
program.
For more detail read : HashMap vs IdentityHashMap - Similarity and Differences with program in java

Collection interview Question 20. What is WeakHashMap in java?


Answer. Another tricky collection framework interview question for experienced developers in java.

java.util.WeakHashMap is hash table based implementation of the Map interface, with weak keys.
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.

java.util.WeakHashMap is implementation of the java.util.Map interface 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.

Collection interview Question 21. What is EnumSet in java?


Answer. Freshers must know about EnumMap in java.
A java.util.EnumSet is specialized Set implementation for use with enum types 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.

Collection interview Question 22. 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?
Answer.

HashMap Custom implementation/ HashMap works in


java

Collection interview Question 24. How to implement own LinkedHashMap in java? Or LinkedHashMap works in java?
Answer.
LinkedHashMap Custom
implementation/How LinkedHashMap works in java

Collection interview Question 25. How to implement own ArrayList in java?Or How ArrayList works in java ?

Answer. ArrayList custom implementation / How


ArrayList works in java

Collection interview Question 26. How to implement own HashSet in java? Or How HashSet works in java ?

Answer. Set Custom implementation/ Or How HashSet works in java

Collection interview Question 27. How to implement own LinkedHashSet in java? Or How LinkedHashSet works in java ?

Answer. LinkedHashSet Custom implementation/ How LinkedHashSet works in java


Collection interview Question 28. 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

For more detail read : ConcurrentModificationException, Fail-fast and Fail-safe in detail in java

Collection interview Question 29. What are different ways of iterating over elements in List?
Answer.
Creating ArrayList and add element.
List<String> arrayList=new ArrayList<String>();
arrayList.add("javaMadeSoEasy");

Iterate over elements in ArrayList using iterator()


iterator() method returns iterator to iterate over elements in ArrayList.

Iterator<String> iterator=arrayList.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
iterator returned by ArrayList is fail-fast.

Iterate over elements in ArrayList using listIterator()


ListIterator<String> listIterator=arrayList.listIterator();
ListIterator returned by ArrayList is also fail fast.

Iterate over elements in list using enumeration


Enumeration<String> listEnum=Collections.enumeration(arrayList);
while(listEnum.hasMoreElements()){
System.out.println(listEnum.nextElement());
}
enumeration is also fail-fast.

Iterate over elements in list using enhanced for loop


for (String string : arrayList) {
System.out.println(string);
}
enhanced for loop is also fail-fast.

Collection interview Question 30. 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");

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.

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.

Iterate over elements in Set using enhanced for loop


for (String string : set) {
System.out.println(string);
}
enhanced for loop is also fail-fast.

Collection interview Question 31. 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");
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
*/
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..

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..

Collection interview Question 32. What is difference between Comparable and Comparator? How can you sort List?
Answer.

Property Comparable Comparator

1 Comparing Comparable is used to compare instances Comparator can be used to compare instances of
instances of class of same class same or different classes.

2 sorting order Comparable can be implemented by class Comparator is implemented when one wants a
which need to define a natural ordering for different sorting order and define custom way of
its objects. comparing two instances.
Example - String, Integer, Long , Date and
all other wrapper classes implements
Comparable.

3 Changes to class For using Comparable, original Class must Class itself can implement Comparator
implement it. or
any other class can implement Comparator.
Hence avoiding modification to original class.

Example- Example-
class Employee implements class ComparatorName implements
Comparable<Employee> Comparator<Employee>

class ComparatorId implements


For using Comparable, Employee Class Comparator<Employee>
must implement it, no other class can
implement it. In above example modifications were made to
ComparatorName and ComparatorId. Hence
As used in Program 1 avoiding modification to Employee class.

As used in Program 4

4 Sorting on basis on Provides sorting only on one criteria, We can use Comparator to sort class on many
one or many because Comparable can be implemented criterias because class itself or any other class can
criteria by original class only. implement Comparator.

5 Method compareTo method compare method

@Override @Override
public int compareTo(Employee obj) { public int compare(Employee obj1, Employee
//sort Employee on basis of obj2) {
name(ascending order) //sort Employee on basis of name(ascending
return this.name.compareTo(obj.name); order)
} return obj1.name.compareTo(obj2.name);
}
Method compares this with obj object and
returns a integer.
Method compares obj1 with obj2 object and
positive – this is greater than obj returns a integer.
zero – this is equal to obj
negative – this is less than obj positive – obj1 is greater than obj2
zero – obj1 is equal to obj2
negative – obj1 is less than obj2

As used in Program 1

As used in Program 3

6 Package java.lang java.util

java.lang package is automatically We need to write explicit import statement -


imported by every program in java.
import java.util.Comparator
Hence, we need to write explicit statement
for importing java.lang.Comparable.

7 Using Let's say we wanna sort list of Employee, Let's say we wanna sort list of Employee,
Collections.sort Collections.sort(list) uses Comparable Collections.sort(list,new ComparatorName());
interface for sorting class. uses Comparator interface for sorting class.
As used in Program 1 As used in Program 5

Read more : Comparable vs Comparator - differences and sorting list by implementing Comparable and Comparator in
classes and inner classes

Collection interview Question 33. How sort method of Collections class works internally?
Answer. Collections.sort internally calls Arrays.sort,
Arrays.Sort() internally uses Merge Sort.
If number of elements is less than 7 then Insertion Sort is used rather than Merge Sort. (because in case elements are
less than 7 it offers better time complexity)

Collection interview Question 34. How can you sort given HashMap on basis of keys?
Answer.

Please Read : Sort Map by key in Ascending and descending order by implementing Comparator interface and overriding
its compare method and using TreeMap

Collection interview Question 35. How can you sort given HashMap on basis of values?
Answer.
Please Read : Sort Map by value in Ascending and descending order by implementing Comparator interface and
overriding its compare method

Collection interview Question 36. In what all possible ways you can sort a given Set?
Answer.
Please Read : Sort Set by using TreeSet and by implementing Comparator and Comparable interface

Collection interview Question 37. How you can sort arrays? And how Comparator of superclass can be used by
subclasses?
Answer.
Please Read : Arrays.sort to sort arrays by implementing Comparator and how Comparator of superclass can be used by
subclasses

Collection interview Question 38. What are differences between ArrayList vs CopyOnWriteArrayList?
Answer.
Differences between java.util.ArrayList and java.util.concurrent.CopyOnWriteArrayList in java >
Property java.util.ArrayList java.util.concurrent.
CopyOnWriteArrayList

1 synchronization ArrayList is not synchronized (because 2 threads on CopyOnWriteArrayList is


same ArrayList object can access it at same time). synchronized (because 2 threads on
same CopyOnWriteArrayList object
I have created program to show see consequence of cannot access it at same time).
using ArrayList in multithreading environment.
In the program i will implement our own arrayList.

2 Iterator and Iterator and listIterator returned by ArrayList are Fail- Iterator and listIterator returned by
listIterator fast, means any structural modification made to CopyOnWriteArrayList are Fail-safe in
ArrayList during iteration using Iterator or listIterator java.
will throw ConcurrentModificationException in java.
As shown in Program 2 below.
As shown in Program 1 below.

3 Enumeration is Enumeration returned by ArrayList is fail-fast, means Enumeration returned by


fail-fast any structural modification made to ArrayList during CopyOnWriteArrayList is fail-safe.
iteration using Enumeration will throw
ConcurrentModificationException.

As shown in Program 1 below.

As shown in Program 2 below.

4 Iterate using Iteration done on ArrayList using enhanced for loop is Iteration done on
enhanced for Fail-fast, means any structural modification made to CopyOnWriteArrayList using
loop ArrayList during iteration using enhanced for loop will enhanced for loop is Fail-safe.
throw ConcurrentModificationException.
As shown in Program 2 below.
As shown in Program 1 below.

5 Performance ArrayList is not synchronized, hence its operations are CopyOnWriteArrayList is


faster as compared to CopyOnWriteArrayList. synchronized, hence its operations
are slower as compared to ArrayList.

6 AbstractList ArrayList extends AbstractList (abstract class) which CopyOnWriteArrayList does not
provides implementation to List interface to minimize extends AbstractList, though
the effort required to implement this interface backed CopyOnWriteArrayList also
by RandomAccess interface. implements RandomAccess interface.

7 Introduced in ArrayList was introduced in second version of java (1.2) CopyOnWriteArrayList was
which java i.e. JDK 2.0 introduced in fifth version of java
version (1.5) i.e. JDK 5.0

8 Package java.util java.util.concurrent


For more detail read : ArrayList vs CopyOnWriteArrayList - Similarity and Differences with program

Collection interview Question 39. What are differences between HashSet vs CopyOnWriteArraySet?
Answer.
Differences between java.util.HashSet and java.util.concurrent.CopyOnWriteArraySet in java >
Property java.util.HashSet java.util.concurrent.
CopyOnWriteArraySet

1 synchronization HashSet is not synchronized (because 2 threads on CopyOnWriteArraySet is synchronized


same HashSet object can access it at same time) in (because 2 threads on same
java. CopyOnWriteArraySet object cannot
access it at same time) in java.

2 Iterator Iterator returned by HashSet is Fail-fast, means any Iterator returned by


structural modification made to HashSet during CopyOnWriteArraySet is Fail-safe in
iteration using Iterator will throw java.
ConcurrentModificationException in java.
As shown in Program 2 below.
As shown in Program 1 below.
3 Enumeration is Enumeration returned by HashSet is fail-fast, means Enumeration returned by
fail-fast any structural modification made to HashSet during CopyOnWriteArraySet is fail-safe.
iteration using Enumeration will throw
ConcurrentModificationException. As shown in Program 2 below.

As shown in Program 1 below.

4 Iterate using Iteration done on HashSet using enhanced for loop is Iteration done on
enhanced for Fail-fast, means any structural modification made to CopyOnWriteArraySet using enhanced
loop HashSet during iteration using enhanced for loop will for loop is Fail-safe.
throw ConcurrentModificationException.

As shown in Program 1 below.

As shown in Program 2 below.

5 Performance HashSet is not synchronized, hence its operations are CopyOnWriteArraySet is synchronized,
faster as compared to CopyOnWriteArraySet. hence its operations are slower as
compared to HashSet.

6 Introduced in HashSet was introduced in second version of java CopyOnWriteArraySet was introduced
which java (1.2) i.e. JDK 2.0 in fifth version of java (1.5) i.e. JDK 5.0
version

7 Package java.util java.util.concurrent


For more detail read : HashSet vs CopyOnWriteArraySet - Similarity and Differences with program

Collection interview Question 40. What are differences between TreeSet vs ConcurrentSkipListSet?
Answer.
Differences between java.util.TreeSet and java.util.concurrent.ConcurrentSkipListSet in java >
Property java.util.TreeSet java.util.concurrent.
ConcurrentSkipListSet

1 synchronization TreeSet is not synchronized (because 2 threads on ConcurrentSkipListSet is synchronized


same TreeSet object can access it at same time) in java. (because 2 threads on same
ConcurrentSkipListSet object cannot
access it at same time) in java.

2 Iterator Iterator returned by TreeSet is Fail-fast, means any Iterator returned by


structural modification made to TreeSet during ConcurrentSkipListSet is Fail-safe in
iteration using Iterator will throw java.
ConcurrentModificationException in java.

As shown in Program 1 below.

As shown in Program 2 below.

3 Enumeration is Enumeration returned by TreeSet is fail-fast, means Enumeration returned by


fail-fast any structural modification made to TreeSet during ConcurrentSkipListSet is fail-safe.
iteration using Enumeration will throw
ConcurrentModificationException.
As shown in Program 1 below.

As shown in Program 2 below.

4 Iterate using Iteration done on TreeSet using enhanced for loop is Iteration done on
enhanced for Fail-fast, means any structural modification made to ConcurrentSkipListSet using enhanced
loop TreeSet during iteration using enhanced for loop will for loop is Fail-safe.
throw ConcurrentModificationException.
As shown in Program 2 below.
As shown in Program 1 below.

5 Performance TreeSet is not synchronized, hence its operations are ConcurrentSkipListSet is synchronized,
faster as compared to ConcurrentSkipListSet. hence its operations are slower as
compared to TreeSet.

6 Introduced in TreeSet was introduced in second version of java (1.2) ConcurrentSkipListSet was introduced
which java i.e. JDK 2.0 in sixth version of java (1.6) i.e. JDK 6.0
version

7 Package java.util java.util.concurrent


For more detail read : TreeSet vs ConcurrentSkipListSet - Similarity and Differences with program

Collection interview Question 41. What are differences between TreeMap vs ConcurrentSkipListMap?
Answer.
Differences between java.util.TreeMap and java.util.concurrent.ConcurrentSkipListMap in java >
Property java.util.TreeMap java.util.concurrent.
ConcurrentSkipListMap

1 synchronization TreeMap is not synchronized (because 2 threads on ConcurrentSkipListMap is synchronized


same TreeMap object can access it at same time) in (because 2 threads on same
java. ConcurrentSkipListMap object cannot
access it at same time) in java.

2 Iterator The iterators returned by the iterator() method of The iterators returned by the iterator()
Map's “collection view methods" are fail-fast> method of Map's “collection view
map.keySet().iterator() methods" are fail-safe >
map.values().iterator() map.keySet().iterator()
map.entrySet().iterator() map.values().iterator()
map.entrySet().iterator()
all three iterators are fail-fast, means any structural
modification made to TreeMap during iteration all three iterators are fail-safe.
using any of 3 Iterator will throw
ConcurrentModificationException.

As shown in Program 1 below.


As shown in Program 2 below.

3 Performance TreeMap is not synchronized, hence its operations ConcurrentSkipListMap is synchronized,


are faster as compared to ConcurrentSkipListMap. hence its operations are slower as
compared to TreeMap.
4 Introduced inin TreeMap was introduced in second version of java ConcurrentSkipListMap was introduced
which java i.e. JDK 2.0 in sixth version of java i.e. JDK 6.0
version

5 Package java.util java.util.concurrent

6 Implements Map Map


which interface SortedMap SortedMap
NavigableMap NavigableMap
ConcurrentNavigableMap
For more detail read : TreeMap vs ConcurrentSkipListMap - Similarity and Differences with program

Collection interview Question 43. Can we use null element in TreeSet? Give reason?
Answer. No, TreeSet does not allows to store any null keys.
Any attempt to add null throws runtimeException (NullPointerException).

TreeSet internally compares elements for sorting elements by natural order (comparator may be used for sorting, if
defined at creation time) and null is not comparable, Any attempt to compare null with other object will throw
NullPointerException.

Collection interview Question 44. Can we use null key in TreeMap? Give reason?
Answer. No, TreeMap not allow to store null key.
Any attempt to store null key throws runtimeException (NullPointerException).
TreeMap internally compares keys for sorting keys by natural order (comparator may be used for sorting, if defined at
creation time) and null is not comparable, Any attempt to compare null with other object will throw
NullPointerException.

Collection interview Question 45. How ConcurrentHashMap works? Can 2 threads on same ConcurrentHashMap object
access it concurrently?
Answer. ConcurrentHashMap is divided into different segments based on concurrency level. So different threads can
access different segments concurrently.

Can threads read the segment locked by some other thread?


Yes. When thread locks one segment for updation it does not block it for retrieval (done by get method) hence some
other thread can read the segment (by get method), but it will be able to read the data before locking.

For operations such as putAll concurrent retrievals may reflect removal of only some entries.
For operations such as clear concurrent retrievals may reflect removal of only some entries.

Segments in ConcurrentHashMap with diagram >


we have ConcurrentHashMap with 4 segments -
(Diagram shows how segments are formed in ConcurrentHashMap)
Collection interview Question 46. Write a program to show consequence of using ArrayList in multithreading
environment?
Answer. Program to show consequence of using ArrayList in multithreading environment in java

Collection interview Question 47. Write a program to show advantage of using Vector in multithreading environment?
Answer. Program to show advantage of using Vector in multithreading environment in java

Collection interview Question 48. Mention properties of most frequently used Collection classes and Interfaces?
Mention as many properties as much you can.
Answer. This question is real test for experienced developers, this will test your in depth awareness of Collection classes
and Interfaces. Answering this question in detail will really ensure your selection.

List Duplicate insertion Sorted by synchronized null Iterator


elements order natural elements
order

ArrayList Yes Yes Yes Iterator & listIterator


are
Fail-fast

LinkedList Yes Yes Yes Iterator & listIterator


are
Fail-fast

CopyOnWriteArrayList Yes Yes Yes Yes Iterator & listIterator


are
Fail-safe

Set Duplicate insertion Sorted by synchronized null Iterator


elements order natural elements
order

HashSet Yes Fail-fast

LinkedHashSet Yes Yes Fail-fast

TreeSet Yes No Fail-fast

ConcurrentSkipListSet Yes Yes No Fail-safe

Map Duplicate insertion Sorted by synchronized null keys or Iterator


Keys order of natural null values
keys order of Map implementations
keys returns 3 iterators >
map.keySet().iterator()
map.values().iterator()
map.entrySet().iterator()

HashMap one null key All are Fail-fast


and many
null values

Hashtable Yes No All are Fail-fast

ConcurrentHashMap Yes No All are Fail-safe

TreeMap Yes Null key not All are Fail-fast


allowed,
Allow many
null values

ConcurrentSkipListMap Yes Yes No All are Fail-safe


Collection - List, Set and Map all properties in tabular form

Collection interview Question. 49 Which list class must be preferred in multithreading environment, considering
performance constraint?
Answer. CopyOnWriteArrayList

Collection interview Question 50. Which Set class must be preferred in multithreading environment, considering
performance constraint?
Answer. CopyOnWriteArraySet (allows null and elements aren't sorted in natural order) or ConcurrentSkipListSet
(doesn’t allows null and elements are sorted in natural order)
Select one depending on your requirement.

Collection interview Question 51. Which Map class must be preferred in multithreading environment, considering
performance constraint?
Answer. ConcurrentHashMap(keys aren't sorted in natural order) or ConcurrentSkipListMap(keys are sorted in natural
order)
Select one depending on your requirement.

Collection interview Question 52. Let’s say you have to build dictionary and multiple users can add data in that
dictionary? And you can use 2 Collection classes? Which Collection classes you will prefer and WHY?
Answer. It’s very important question which test your logical reasoning and your ability to create robust applications in
multithreading environment.

We must use ConcurrentSkipListMap and TreeSet >


ConcurrentSkipListMap<String, TreeSet<String>> myDictionary =
new ConcurrentSkipListMap<String, TreeSet<String>>();

Store words in ConcurrentSkipListMap as key>


keys are sorted in natural order (words will be sorted in natural order),
doesn’t allow null keys (words can’t be null)
doesn’t allow duplicate keys (words can’t be duplicate) and
synchronized, so 2 threads won’t create synchronization problems (will take care of different uses adding words
concurrently)

for storing meaning of word in dictionary we must use TreeSet as value in ConcurrentSkipListMap because one word can
have many meanings >
elements are sorted in natural order (meaning of word are sorted in natural order),
doesn’t allow null elements (meaning of word can’t be null),
doesn’t allow duplicate elements (meaning of word can’t be duplicate)

Program for creating and using Java dictionary using Collection classes>
package com.ankit.dictionary;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentSkipListMap;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class MyDictionary {
public static void main(String[] args) {
ConcurrentSkipListMap<String, TreeSet<String>> myDictionary =
new ConcurrentSkipListMap<String, TreeSet<String>>();
TreeSet<String> innocentMeaning = new TreeSet<String>();
innocentMeaning.add("not responsible for an event yet suffering its consequences");
innocentMeaning.add("not guilty of a crime");
myDictionary.put("innocent", innocentMeaning);
TreeSet<String> appealingMeaning = new TreeSet<String>();
appealingMeaning.add("attractive");
appealingMeaning.add("expressing a desire for help");
myDictionary.put("appealing", appealingMeaning);
System.out.println(myDictionary);
}
}
/* OUTPUT
{appealing=[attractive, expressing a desire for help], innocent=[not guilty of a crime, not responsible for an event yet
suffering its consequences]}
*/

Collection interview Question 53. Why to use java.util.WeakHashMap map which is so inconsistent and unpredictable in
behaviour?
Answer. Let's say we have huge application which consists of lots n lots of object and may run short of memory at any
time, we will like garbage collector to quickly discard less used key value pair to free up some memory. As, behavior of
the WeakHashMap class depends upon garbage collector.
I believe discarding less used key-value is always going to a better option than running out of memory.

You might also like