Collection framework
|
1. What is the
limitation of Object Arrays?
The main limitations of Object arrays are
•
These are fixed in size i.e once we created an
array object there is no chance of increasing or decreasing size based on our
requirement. Hence If we don’t know size in advance , arrays are not
recommended to use
•
Arrays can hold only homogeneous elements.
•
There is no underlying data structure for
arrays and hence no readymade method support for arrays. Hence for every
requirement programmer has to code explicitly
To over come these problems collections are recommended to us
To over come these problems collections are recommended to us
2. What is the
difference between the Arrays and Collections?
Array
|
Collection
|
Arrays are of fixed size
|
Collections are growable in size
|
For memory usage Arrays are not recommended to use
|
For memory allocation Collections are recommended to use
|
In terms of performance Arrays are better
|
In terms of performance Collections are slower
|
Arrays can hold homogeneous data element
|
Collections can hold homogeneous and heterogeneous data
|
Arrays can hold primitives and objects
|
Collections can hold only objects
|
There is no underlying data structure available so ready made
data support is not available
|
For each Collection class there is underlying data structure
so upon requirement ready made data support is available for collection
|
3. What is the difference between the Arrays and ArrayList?
Array
|
ArrayList
|
Stores primitive data types and also objects
|
Stores only objects
|
Defined in Java language itself as a fundamental data
structure
|
Belongs to collections framework
|
Fixed size
|
Growable and resizable. Elements can be added or removed
|
Stores similar data of one type
|
Can store heterogeneous data types
|
It is not a class
|
It is a class with many methods
|
Cannot be synchronized
|
Can be obtained a synchronized version
|
Elements retrieved with for loop
|
Can be retrieved with for loop and iterators
|
Elements accessible with index number
|
Accessing methods like get() etc. are available
|
Can be multidimensional
|
—
|
4. What is the difference between the Arrays and Vectors?
Array
1)Size of array need to be declared in advance.
2)Once declared array can't grow in size.
3)Array can store primitive data types. like int, char,...
Vector
1) No need to declare the size of vector. You may give its size & you may not.
2) Vector can always grow in size if you start adding more element to it than your declared size.
3) Vector can store only object references. Storing primitive data types is not possible in case of vectors
5. What is the Collection API?
1)Size of array need to be declared in advance.
2)Once declared array can't grow in size.
3)Array can store primitive data types. like int, char,...
Vector
1) No need to declare the size of vector. You may give its size & you may not.
2) Vector can always grow in size if you start adding more element to it than your declared size.
3) Vector can store only object references. Storing primitive data types is not possible in case of vectors
5. What is the Collection API?
•
The Collection API is a set
of classes and interfaces that support operation on collections of objects.
•
These classes and interfaces
are more flexible, more powerful, and more regular than the vectors, arrays,
and hash tables if effectively replaces.
6. What is the Collection Framework?
A Collections Framework
mainly contains the following 3 parts
•
A Collections Framework
is defined by a set of interfaces, concrete class implementations
for most of the interfaces and a set of standard
utility methods and algorithms.
•
In addition, the framework also provides
several abstract implementations, which are designed to make it easier for you
to create new and different implementations for handling collections of
data.
7. What is the difference between the Collections and Collection?
•
Collection is a base
interface for most collection classes (it is the root interface of java
collection framework) Collections is a utility class
•
Collections class is a
utility class having static methods It implements Polymorphic algorithms which
operate on collections
8. Explain about Collection interface?
•
This interface can be used to
represent a group of objects as a single entity.
•
It acts as root interface for
entire collection framework.
•
It defines the most commonly
used methods which can be applicable for any collection implemented class
object
Q9. Explain about List interface?
List interface is a child
interface of Collection interface. This can be used to represent group of
individual objects in as a single entity where
•
Duplicates are allowed
•
Insertion order is preserved
Q10. Explain about Set interface?
Set is a child interface of
Collection interface. it can be used to represent a group of individual objects
as a single entity where
•
Duplicate objects are not
allowed.
•
Insertion order is not
preserved
Q11. Explain about SortedSet interface?
it is child interface of Set interface. it can be used to
represent a group of individual objects in to a single entity where
•
All the objects are arranged
in some sorting order (Can be natural sorting order or customizede).
•
Duplicates are not allowed.
Q12. Explain about NavigableSet ?
It is child interface of
SortedSet and provides several utility methods for navigation purposes
•
It doesn’t allows
duplicates
•
Insertion order is preserved
•
It is introduced in 1.6
version
Q13. Explain about Queue interface?
If we want to represent a
group of individual objects prior to processing, then we should go for Queue
interface. It is child interface of Collection interface.
It has introduced in 1.5
version.
Q14. Explain about Map interface?
Remember it is not a child
Interface of Collection Interface and hence Map and Collection Interfaces
doesn’t have any relationship.
•
It can be used for
representing a group of Objects as key, value pairs.
•
Both keys and values should
be objects
•
Keys can t be duplicated but
values can be duplicated.
•
it has introduced in
1.2 version
Q15. Explain about SortedMap ?
•
If we want to represent a
group of objects as key value pairs where all the entries are arranged
according some sorting order of keys then we should go for SortedMap.
•
It is child interface of Map.
•
It has introduced in
1.2 version
Q16. Explain about NavigableMap?
•
It is child interface of
SortedMap and defines several method for navigation purpose
•
It is introduced in 1.6
version
Q17. Explain about ArrayList class?
ArrayList is a Collection
which can be used to represent a group of objects as a single entity.
•
it is a implemented class
for List interface
•
Introduced in 1.2 version
•
The underlying data structure
is resizable or growable array.
•
Insertion order is preserved
•
Duplicates are allowed
•
Heterogeneous objects are
allowed
•
null insertion is possible
•
This class implements
RandomAccess , Serializable , Cloneable interfaces
•
Best choice for
retrieval purpose and worst if our frequent operation is insertion or deletion
in the middle
Q18. What is RandomAccess Interface?
•
If a collection class
implements RandomAccess interface then we can access any of its element with
the same speed.
•
RandomAccess interface is
marker interface and it dosent contains any methods.
•
ArrayList and vector classes
implements this interface.
•
It is a Marker interface used by List
implementations to indicate that they support fast (generally constant time)
random access.
•
The primary purpose of this interface is to
allow generic algorithms to alter their behavior to provide good performance
when applied to either random or sequential access lists.
Q19. Explain about LinkedList class?
LinkedList is a Collection
implemented class which can be used for representing a group of objects as a
single entity.
•
LinkedList is the
implemetation class for List interface
•
Introduced in 1.2 version
•
Underlying data Structure
is DoubleLinkedList
•
Allows duplicates
•
Insertion order is preserved
•
Allows heterogeneous objects
•
null insertion is possible
•
LinkedList class implements
Seriallizable and Cloneable interface but not RandomAccess interface
•
Best choice if frequent
operation is insertion or deletion an objects in middle but worst choice
if frequent operation is retrieval.
Q20. Explain about Vector class?
Vector is a legacy collection class which can be used to
represent a group of objects.
•
Introduced in 1.0 version. it
is legacy class
•
The underlying data structure
is resizable or growable array.
•
Insertion order is preserved
•
Duplicates are allowed
•
Heterogeneous objects are
allowed
•
It is a implemented class
for List interface
•
null insertion is possible
•
Vector class implements
RandomAccess ,Serializable,Cloneable interfaces
•
Best Choice if frequent
operation is retrieval and worst choice if frequent operation is insertion or
deletion in the middle.
•
All methods present in Vector
class are synchronized hence Vector class object is thread safe
21. What is the difference between the ArrayList and Vector?
•
Synchronization:
•
ArrayList is non-synchronized
which means multiple threads can work on ArrayList at the same time. For e.g.
if one thread is performing an add operation on ArrayList, there can be an
another thread performing remove operation on ArrayList at the same time in a
multithreaded environment
•
While Vector is synchronized.
This means if one thread is working on Vector, no other thread can get a hold
of it. Unlike ArrayList, only one thread can perform an operation on vector at
a time.
•
Resize:
•
Both ArrayList and Vector can
grow and shrink dynamically to maintain the optimal use of storage; however the
way they resized is different. ArrayList grow by half of its size when resized
while Vector doubles the size of itself by default when grows.
•
Performance:
•
ArrayList gives better
performance as it is non-synchronized. Vector operations gives poor performance
as they are thread-safe, the thread which works on Vector gets a lock on it
which makes other thread wait till the lock is released.
•
fail-fast:
•
First let me explain what is
fail-fast: If the collection (ArrayList, vector etc) gets structurally modified
by any means, except the add or remove
methods of Iterator, after creation of Iterator then the Iterator will
throw ConcurrentModificationException. Structural modification refers to the addition or deletion
of elements from the collection.
•
As per the Vector javadoc the
Enumeration returned by Vector is not fail-fast. On the other side the Iterator
and listIterator returned by ArrayList are fail-fast.
•
Who belongs to collection framework really?
•
The vector was not the part
of collection framework; it has been included in collections later. It can be
considered as Legacy code. There is nothing about Vector which List collection
cannot do. Therefore Vector should be avoided. If there is needs of thread-safe
operation make ArrayList synchronized or use CopyOnWriteArrayList which
is a thread-safe variant of ArrayList.
There are few similarities between these classes which are as follows:
•
Both Vector and ArrayList use
growable array data structure.
•
The iterator and listIterator
returned by these classes (Vector and ArrayList) are fail-fast.
•
They both are ordered
collection classes as they maintain the elements insertion order.
•
Vector & ArrayList both
allows duplicate and null values.
•
They both grows and shrinks
automatically when overflow and deletion happens.
When to use ArrayList and when to use vector?
•
It totally depends on the
requirement. If there is a need to perform “thread-safe” operation the vector
is your best bet as it ensures that only one thread access the collection at a
time.
•
Performance: Synchronized
operations consumes more time compared to non-synchronized ones so if there is
no need for thread safe operation, ArrayList is a better choice as performance
will be improved because of the concurrent processes.
How
to make ArrayList synchronized?
As I stated above ArrayList methods are non-synchronized but still if there is a need you can make them synchronized like this –
As I stated above ArrayList methods are non-synchronized but still if there is a need you can make them synchronized like this –
//Use Collecions.synzhonizedList method
List list = Collections.synchronizedList(new
ArrayList());
...
//If you wanna use iterator on the
synchronized list, use it
//like this. It should be in synchronized
block.
synchronized (list) {
Iterator iterator = list.iterator();
while
(iterator.hasNext())
...
iterator.next();
...
}
•
Synchronization and Thread-Safe
Vector is synchronized while ArrayList is not synchronized . Synchronization and thread safe means at a time only one thread can access the code .In Vector class all the methods are synchronized .Thats why the Vector object is already synchronized when it is created .
2. Performance
Vector is slow as it is thread safe . In comparison ArrayList is fast as it is non synchronized . Thus in ArrayList two or more threads can access the code at the same time , while Vector is limited to one thread at a time.
3. Automatic Increase in Capacity
A Vector defaults to doubling size of its array . While when you insert an element into the ArrayList , it increases
its Array size by 50% .
By default ArrayList size is 10 . It checks whether it reaches the last element then it will create the new array ,copy the new data of last array to new array ,then old array is garbage collected by the Java Virtual Machine (JVM) .
4. Set Increment Size
ArrayList does not define the increment size . Vector defines the increment size .
You can find the following method in Vector Class
public synchronized void setSize(int i) { //some code }
There is no setSize() method or any other method in ArrayList which can manually set the increment size.
5. Enumerator
Other than Hashtable ,Vector is the only other class which uses both Enumeration and Iterator .While ArrayList can only use Iterator for traversing an ArrayList .
6. Introduction in Java
java.util.Vector class was there in java since the very first version of the java development kit (jdk).
java.util.ArrayList was introduced in java version 1.2 , as part of Java Collections framework . In java version 1.2 , Vector class has been refactored to implement the List Inteface .
Vector is synchronized while ArrayList is not synchronized . Synchronization and thread safe means at a time only one thread can access the code .In Vector class all the methods are synchronized .Thats why the Vector object is already synchronized when it is created .
2. Performance
Vector is slow as it is thread safe . In comparison ArrayList is fast as it is non synchronized . Thus in ArrayList two or more threads can access the code at the same time , while Vector is limited to one thread at a time.
3. Automatic Increase in Capacity
A Vector defaults to doubling size of its array . While when you insert an element into the ArrayList , it increases
its Array size by 50% .
By default ArrayList size is 10 . It checks whether it reaches the last element then it will create the new array ,copy the new data of last array to new array ,then old array is garbage collected by the Java Virtual Machine (JVM) .
4. Set Increment Size
ArrayList does not define the increment size . Vector defines the increment size .
You can find the following method in Vector Class
public synchronized void setSize(int i) { //some code }
There is no setSize() method or any other method in ArrayList which can manually set the increment size.
5. Enumerator
Other than Hashtable ,Vector is the only other class which uses both Enumeration and Iterator .While ArrayList can only use Iterator for traversing an ArrayList .
6. Introduction in Java
java.util.Vector class was there in java since the very first version of the java development kit (jdk).
java.util.ArrayList was introduced in java version 1.2 , as part of Java Collections framework . In java version 1.2 , Vector class has been refactored to implement the List Inteface .
22. How we can
get synchronized version of ArrayList?
ArrayList is not synchronized. But there's a way to get it
synchronized:-
one as mentioned in
java.util.ArrayList's JavaDoc:
List list = Collections.synchronizedList(new ArrayList(...));
In java.util.Collections' JavaDoc you can read that "It is imperative
that the user manually synchronize on the returned list when iterating
over it:"
synchronized(list) {
Iterator i = list.iterator(); // Must be in synchronized block
while (i.hasNext())
foo(i.next());
}
Using a synchronized ArrayList results in additional work
List list = Collections.synchronizedList(new ArrayList(...));
In java.util.Collections' JavaDoc you can read that "It is imperative
that the user manually synchronize on the returned list when iterating
over it:"
synchronized(list) {
Iterator i = list.iterator(); // Must be in synchronized block
while (i.hasNext())
foo(i.next());
}
Using a synchronized ArrayList results in additional work
23. What is the
difference between the Size and capacity of a Collection Object?
•
The size is the number of
elements actually stored in the vector
•
Capacity is the maximum
number of elements it can store at a given instance of time.
24. What is the
difference between the ArrayList and LinkedList?
1) Search:
•
ArrayList search operation is
pretty fast compared to the LinkedList search operation. get(int
index) in ArrayList gives the performance of O(1) while
LinkedList performance is O(n).
Reason:
•
ArrayList maintains index
based system for its elements as it uses array data structure implicitly which
makes it faster for searching an element in the list.
•
On the other side LinkedList
implements doubly linked list which
requires the traversal through all the elements for searching an element.
2) Deletion:
•
LinkedList remove operation
gives O(1) performance while ArrayList gives variable
performance: O(n) in worst case (while removing first element)
and O(1) in best case (While removing last element).
Conclusion: LinkedList element deletion is
faster compared to ArrayList.
Reason:
•
LinkedList’s each element
maintains two pointers (addresses) which points to the both neighbor elements
in the list. Hence removal only requires change in the pointer location in the
two neighbor nodes (elements) of the node which is going to be removed.
•
While In ArrayList all the
elements need to be shifted to fill out the space created by removed element.
3) Inserts
Performance:
•
LinkedList add method
gives O(1) performance while ArrayList gives O(n) in worst
case. Reason is same as explained for remove.
4) Memory
Overhead:
•
ArrayList maintains indexes
and element data while LinkedList maintains element data and two pointers for
neighbor nodes hence the memory consumption is high in LinkedList
comparatively.
There are few similarities between these classes which are as follows:
•
Both ArrayList and LinkedList
are implementation of List interface.
•
They both maintain the
elements insertion order which means while displaying ArrayList and LinkedList
elements the result set would be having the same order in which the elements
got inserted into the List.
•
Both these classes are
non-synchronized and can be made synchronized explicitly by using Collections.synchronizedList method.
•
The Iterator and listIterator
returned by these classes are fail-fast (if list is structurally modified at
any time after the iterator is created, in any way except through the
iterator’s own remove or add methods, the iterator will throw a ConcurrentModificationException).
When to use LinkedList and when to use ArrayList?
1) As explained above the insert and remove
operations give good performance (O(1)) in LinkedList compared to
ArrayList(O(n)). Hence if there is a requirement of frequent addition and
deletion in application then LinkedList is a best choice.
2) Search (get method) operations are fast in
Arraylist (O(1)) but not in LinkedList (O(n)) so If there are less add and
remove operations and more search operations requirement, ArrayList would be
your best bet.
25. What are
legacy classes and interface present in Collection framework?
•
Enumeration ---Interface
•
Dictonary ------Abstract
class
•
Hashtable -----Concrete class
•
Properties -----Concrete
class
•
Vector -----Concrete class
•
Stack -----Concrete
class
26. What is the
difference between the Enumeration and Iterator?
•
As all of you know both
Iterator and Enumeration are used to traverse Collection objects, in a sequential fashion. Enumeration
can be applied to Vector and HashTable. Iterator can be used with most of
the Collectionobjects.
Differences between Iterator & Enumeration:
•
Enumeration is twice as fast
as Iterator and uses very less memory. Enumeration is very basic and fits to
basic needs.
•
But Iterator is much safer as
compared to Enumeration, b’ coz it always denies other threads to
modify the collection object which is being iterated by it. Whenever a
second thread tries for that Iterator will throw a ConcurrentModificationException. Iterators that do this are known
as fail-fast iterators, as they
fail quickly and cleanly.
•
But Iterator provides a safer
way to remove elements from the underlying collection during the iteration with
well-defined semantics. But here the remove() is supported by only those
implementations of Collection that
supports element removal.
Note: Iterator.remove() is the only safe way to modify a collection
during iteration. In Enumeration, there is “no safe way” to remove elements from a collection while traversing.
27. What are the limitations of Enumeration?
•
While iterating the elements
we are not allowed to perform removal operation
•
It is applicable only for
legacy classes and it is not a universal cursor.
•
It can retrieve the elements
only in forward direction
28. What is the
difference between the enum and Enumeration?
•
To be short, Enumeration is legacy Iterator and Enum is a data type.
•
Enums are instance controlled
classes in java. You can predefine the different flavors, a type can support.
For ex.
public enum Direction {
EAST, WEST, NORTH, SOUTH
}
defines a type named Direction which
can be of 4 types. It's not permitted to instantiate these types from outside
their type definition.
•
While Enumeration was the old way to
iterate through a collection. It has two methods nextElement andhasMoreElements which
are more like next and hasNext methods of Iterator interface. In old APIs
like Servlet we can still see
some methods which return Enumeration.
•
Ex:
Java.util.Enumeration<String> paramNames = request.getParameterNames();
29. What is the
difference between the Iterator and ListIterator?
1) Iterator is used for
traversing List and Set both.
We
can use ListIterator to traverse List only. We cannot
traverse Set using ListIterator.
2) We can traverse in only forward direction using Iterator.
Using ListIterator,
we can traverse a List in both the directions (forward and backward).
3) We cannot obtain indexes while using Iterator
We can obtain
indexes at any point of time while traversing a list using ListIterator.
The methods nextIndex() and
previousIndex() are used for this purpose.
4) We cannot add element to collection while traversing it
using Iterator, it throws ConcurrentModificationException when you try to do
it.
We can add element at any point of time while traversing a
list using ListIterator.
5) We cannot replace the existing element value when using
Iterator.
By using set(E e) method of ListIterator we can replace the
last element returned by next() or previous() methods.
6) Methods of Iterator:
•
hasNext()
•
next()
•
remove()
Methods of ListIterator:
•
add(E e)
•
hasNext()
•
hasPrevious()
•
next()
•
nextIndex()
•
previous()
•
previousIndex()
•
remove()
•
set(E e)
Iterator
|
ListIterator
|
Can do remove operation only on elements
|
Can remove, add and replace elements
|
Method is remove()
|
Methods are remove(), add() and set()
|
iterator() method returns an object of Itertor
|
listIterator() method returns an object of ListItertor
|
iterator() method is available for all collections. That is,
Iterator can be used for all collection classes
|
listIterator() method is available for those collections
that implement List
interface. That is, descendents of List interface
only can use
ListIterator
|
•
Both are interfaces introduced with JDK 1.2
only. Both comes with the same methods of iteration and retrieval – hasNext() and next(). Both iterators are fail-fast.
30. What is the relation between the Iterator and ListIterator?
ListIterator is child interface of Iterator
31. Explain about HashSet class?
•
The underlying data structure
is Hashtable
•
null values are accepted
•
duplicates are not allowed
•
insertion order is based on
hashcode of the object hence insertion order is not preserved
•
best suitable if
frequent operation is search operations
•
HashSet class
implements Serializable and Cloneable
•
it is implementation class for
Set interface
•
heterogeneous objects are
allowed
•
it is introduced in 1.2
version
32. If we are trying to insert duplicate values in Set what
will happen?
•
If we are trying to insert
duplicate objects to the HashSet , we wont get any compile time or run time
errors just the add(Object o) returns false and it doesn’t add that object.
(Or)
•
If we insert duplicate values
to the Set, we don’t get any compile time or run time errors. Just it doesn’t
add duplicate values.
•
Boolean add(E e) -
Adds the specified element to this set if it is not already present (optional
operation).
•
As add() method returns
Boolean and on adding duplicates it will return false.
33. What is LinkedHashSet?
•
It is the child class of
HashSet. The main difference between HashSet and LinkedHashSet is:
•
In the case of HashSet
insertion order is not preserved , but in the case of LinkedHashSet insertion
will be preserved.
34. Differences between HashSet and LinkedHashSet?
HashSet
|
LinkedHashSet
|
1The Underlying datastructure is Hashtable
|
1The underlying datastructure is combination of LinkedList and
Hashtable
|
2Insertion Order is not preserved
|
2
Insertion order is preserved.
|
3Introduced in 1.2 version
|
3
Introduced in 1.4 version
|
35. What are major enhancements in 1.4 version of collection
frame work?
LinkedHashSet
LinkedHashMap
IdentityHashMap
LinkedHashMap
IdentityHashMap
36. Explain about TreeSet?
It is Collection object which can be used to represent a group of objects according to some sorting order.
It is Collection object which can be used to represent a group of objects according to some sorting order.
•
The underlying datastructure
is Balanced tree
•
Duplicates are not allowed
•
All objects are stored
according to some sorting order hence insertion order is not preserved
•
Heterogeneous objects are not
allowed violation leads to ClassCastException
•
For an Empty TreeSet as firs
element null value can be inserted but after inserting that first value if we
are trying to insert any other objects then we will get NullPointerException
•
For an non empty TreeSet if
we are trying to inser null value at run time u will get
NullPointerException
37. What are differences between List and Set interfaces?
List
|
Set
|
1Insertion Order is preserved
|
1Insertion Order is not preserved
|
2Duplicate Objects are allowed
|
2
Duplicate Objects are not allowed
|
3The implemented classes are ArrayList,LinkedList , Vector and
Stack classes
|
3 The
implemented classes are HashSet,
LinkedHashSet
and Tree
|
38. What is Comparable interface?
•
This interface can be used
for defining natural sorting order of the objects.
•
It is present in java.lang
package
•
It contains a method
public int compareTo(Object obj1)
39. What is Comparator interface?
•
This interface can be used
for implementing customized sorting order.
•
It is present in java.util
package
•
It contains two methods
•
public int compare(Object ,Object)
•
public boolean equals(Object)
40. What are differences
between Comparable and Comparator?
Comparable
|
Comparator
|
1This can be used for natural sorting order
|
1This can be used for implementing customized sorting
|
2This interface present in java.lang package
|
2
This is present in java.util package
|
3Contains only one method:
public int
compareTo(Object obj1)
|
3
It contains two methods.
public int compare(Object ,Object) public Boolean equals(Object) |
4
It is marker interface
|
4 It is not a
marker interface.
|
41. What is the difference between the HashSet and TreeSet?
HashSet
|
TreeSet
|
1The underlying data structure is Hashtable
|
1The underlying data structure is balanced tree
|
2Heterogeneous objects are allowed
|
2
Heterogeneous objects are not allowed bydefalut
|
3Insertion order is not preserved and it is based on hashcode
of the objects
|
3
Insertion order is not preserved and all the objects are inserted according
to some sorting order.
|
4null insertion is possible
|
4 As the
first element only null insertion is possible and in all other
cases we will get NullPointerException
|
42. What is Entry interface?
It is
inner interface of Map.
In the Map each key value pair is considered as Entry object.
interface Map{
//more code here
interface Entry{
Object getKey()
Object getValue()
Object setValue(Object new)
}
}
43. Explain about HashMap?
In the Map each key value pair is considered as Entry object.
interface Map{
//more code here
interface Entry{
Object getKey()
Object getValue()
Object setValue(Object new)
}
}
43. Explain about HashMap?
It is a Map Object which can be used used to represent a
group of objects as key-value pairs.
•
The underlying data structure
is Hashtable
•
Duplicaes keys are not
allowed duplicate values are allowed
•
Insertion order is not
preserved because insertion is based on hashcode of keys.
•
Heterogeneous objects are
allowed for both keys and values
•
null key is allowed
only once
•
null values are allowed
multiple times
•
Introduced in 1.2 version
44. Explain About LinkedHashMap?
It is child class of HashMap.
It is exactly same as HashMap except the following difference.
In the case of HashMap the
insertion order is not preserved but in the case of LinkedHashMap insertion
order is preserved. Introduced in 1.4 version
45. What is the difference between the HashMap and LinkedHashMap?
HashMap
|
LinkedHashMap
|
1.The underlying data structure is Hashtable
|
1.The underlying data structure is a combination of Hashtable
and linkedlist
|
2.Insertion order is not preserved and it is based on hashcode
of keys
|
2
Insertion order is preserved
|
3.Introduced in 1.2 version
|
3
Introduced in 1.4 version.
|
46 What is the difference between the HashMap and Hashtable?
HashMap
|
Hashtable
|
1.The underlying data structure is Hashtable
|
1.The underlying data structure of Hashtable
|
2.No method is synchronized and hence HashMap object is not
thread safe
|
2 .All methods
are synchronized and hence it is thread safe
|
3.Performance is high
|
3.
Performance is low
|
4.null insertion is possible for both keys and values
|
4. null
insertion is not possible for both key and value violation leads to
NullPointerException
|
5.Introduced in 1.2 version and it is non legacy
|
5.
Introduced in 1.0 version and it is legacy
|
47 What is Identity HashMap?
It is exactly same as HashMap
except the following difference.
•
In the HashMap JVM uses
equals() method to identify duplicate keys but in the case of
IdentityHashMap JVM uses == operator for this.
48. What is the difference between the HashMap and
IdentityHashMap?
49. what is weakHashMap?
49. what is weakHashMap?
It is
exactly same as HashMap except the following difference.
•
In case of HashMap an Object
is not eligible for garbage collection if it is associated with HashMap even
though it dosent have any external references. ie HashMap dominates
garbage collector.
•
But in case of WeakHashMap ,
if an Object is not having any external references then it is always eligible
for garabage collectoion even though it is associated with weakHashMap.
ie garbage collector dominates WeakHashMap
50. What is the difference between the HashMap and
WeakHashMap?
•
WeakHashMap is
an implementation of Map interface where the memory of the value object can be
reclaimed by Grabage Collector if the corresponding key is no longer referred
by any section of program.
•
This is different from
HashMap where the value object remain in HashMap even if key is no longer referred. We need to explicitly call
remove() method on HashMap object to remove the value so that it can be ready
to be reclaimed(Provided no other section of program refers to that value
object). Calling remove() is an extra overhead
51. What is TreeMap?
TreeMap can be used to
store a group of objects as key-value pairs where all the entries are arranged
according to some sorting order of keys.
•
The underlying data structure
is RED-BLACK Tree
•
Duplicates keys are not
allowed but values can be duplicated.
•
Insertion order is not
preserved because insertion is based on some sorting order
•
If we are depending on
Natural sorting order then keys should be homogeneous(violation leads to
ClassCastException) but values need not homogeneous
•
In case of customized sorting
order we can insert heterogeneous keys and values
•
For empty TreeMap as first
entry with null values are allowed but after inserting that entry if we are
trying to insert any other entry we will get NullPointerException
•
For non empty TreeMap if we
are trying to insert null keys we will get NullPointerException
•
There are no restrictions for
null values.
52. What is Hashtable
Hashtable is a legacy Map and can be used to store objects as key value pairs.
•
The underlying data
sturucture is Hashtabe
•
Duplicates keys are not
allowed but duplicate values are allowed
•
null insertion is not
possible for both keys and values
•
all methods are synchronized
•
insertion order is not
preserved because it is based on hashcode of keys
•
heterogeneous Objects are
allowed for both keys and values
•
introduced in 1.0 version it
is legacy class
53. What is PriorityQueue?
It represents a data
structure to hold group of individual objects prior to processing based on some
priority .it can be natural sorting order and it can be customized sorting
order described by Comparator.
It is the implementation class of Queue interface.
It is the implementation class of Queue interface.
•
Insertion order is not
preserved because here insertion is done based on some sorting order
•
Duplicates are not allowed
•
null insertion is not
possible even as first element also
•
If we are depending on
natural sorting order Objects should be homogeneous violation leads to
ClassCastException
•
If we are depending on
customized sorting order Objects can be heterogeneous also.
54. What is Arrays class?
•
It is utility class for
arrays.
•
It defines several utility
methods for arrays like sorting an array or searching an element in array
•
present in java.util package
55. We are planning to do an indexed search in a list of
objects. Which of the two Java collections should you use: ArrayList or
LinkedList?
ArrayList
56. Why ArrayList is faster than Vector?
ArrayList
56. Why ArrayList is faster than Vector?
•
All methods present in the
Vector are synchronized and hence any method can be executed by only
one thread at a time. It slows down the execution.
•
But in ArrayList, no
method is synchronized and hence multiple threads are allowed execute
simultaneously which speed up the execution.
57. How can we sort the elements of list?
58. How we can reverse the order of elements of a list?
59. Explain about Collections class?
60. What is the difference between the reverse() and reverseOrder() present in Collections Class?
61. Explain the Arrays Class?
•
The java.util.Arrays class contains a static factory that allows
arrays to be viewed as lists.
•
Following are the important
points about Arrays:
•
This class contains various
methods for manipulating arrays (such as sorting and searching).
•
The methods in this class
throw a NullPointerException if the specified array reference is null.
Class declaration:
public class Arrays
extends Object
62. How we can implement the sorting for Arrays?
63. Is it possible to convert Collection Object into Arrays?
64. Is it possible to convert array into ArrayList form?
yes
65. Explain about BinarySearch() method available in Collections and Arrays Classes?
66. What is the difference between index and insertion point?
67. What is load-factor?
65. Explain about BinarySearch() method available in Collections and Arrays Classes?
66. What is the difference between index and insertion point?
67. What is load-factor?
•
The load factor is a
measure of how full the hash table is allowed to get before its capacity is
automatically increased.
•
Ex: The default initial
capacity of the HashMap will be taken as 16 and the load factor as 0.75. load
factor represents at what level the HashMap capacity should be doubled. For
example the product of capacity and load factor = 16 * 0.75 = 12. This
represents that after storing the 12th key – value pair into the HashMap , its
capacity will become 32