Struts Extra
Struts Extra
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 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.
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.
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.
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.
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 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.
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.Collections is a utility class which consists of static methods that operate on or return Collection 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.
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.
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.
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.
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.
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.
@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.
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.
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.
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.
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.
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.
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.
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.
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.
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
}
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.
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.
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.
5 Implementation HashMap use Hashtable use buckets LinkedHashMap uses TreeMap uses Red
uses? buckets doubly linked lists black tree
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.
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
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
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.
Collection interview Question 23. How to implement own/custom HashMap in java? Or How HashMap works in java?
Answer.
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 ?
Collection interview Question 26. How to implement own HashSet in java? Or How HashSet works in java ?
Collection interview Question 27. How to implement own LinkedHashSet in java? Or How LinkedHashSet works in java ?
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");
Iterator<String> iterator=arrayList.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
iterator returned by ArrayList is 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");
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..
/*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.
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>
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.
@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
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
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.
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.
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
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
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.
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
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
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
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
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.
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.
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.
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.
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.
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.