Java Interview Questions : Series 9
164. What are the differences
between Comparable and
Comparator?
Main differences between Comparable and Comparator are:
1. Type: Comparable<T> is an interface in Java where T is
the type of objects that this object may be compared to.
2. Comparator<T> is also an interface where T is the type of
objects that may be compared by this comparator.
3. Sorting: In Comparable, we can only create one sort
sequence. In Comparator we can create multiple sort
sequences.
4. Method Used: Comparator<T> interface in Java has
method public int compare (Object o1, Object o2) that
returns a negative integer, zero, or a positive integer when
the object o1 is less than, equal to, or greater than the
object o2. A Comparable<T> interface has method public
int compareTo(Object o) that returns a negative integer,
zero, or a positive integer when this object is less than,
equal to, or greater than the object o.
5. Objects for Comparison: The Comparator compares two
objects given to it as input. Comparable interface
compares "this" reference with the object given as input.
6. Package location: Comparable interface in Java is defined
in java.lang package. Comparator interface in Java is
defined in java.util package.
165. In Java, what is the purpose of
Properties file?
A Properties file in Java is a list of key-value pairs that can be
parsed by java.util.Properties class.
Generally a Properties file has extension .properties e.g.
myapp.properties.
Properties files are used for many purposes in all kinds of Java
applications. Some of the uses are to store configuration, initial
data, application options etc.
When we change the value of a key in a properties file, there is no
need to recompile the Java application. So it provides benefit of
changing values at runtime.
166. What is the reason for overriding
equals() method?
The equals() method in Object class is used to check whether two
objects are same or not. If we want a custom implementation we can
override this method.
For example, a Person class has first name, last name and age. If we
want two Person objects to be equal based on name and age, then
we can override equals() method to compare the first name, last
name and age of Person objects.
Generally in HashMap implementation, if we want to use an object
as key, then we override equals() method.
167. How does hashCode() method
work in Java?
Object class in Java has hashCode() method. This method returns a
hash code value, which is an integer.
The hashCode() is a native method and its implementation is not
pure Java.
Java doesn't generate hashCode(). However, Object generates a
HashCode based on the memory address of the instance of the
object.
If two objects are same then their hashCode() is also same.
168. Is it a good idea to use Generics
in collections?
Yes. A collection is a group of elements put together in an order or
based on a property. Often the type of element can vary. But the
properties and behavior of a Collection remains same. Therefore it
is good to create a Collection with Generics so that it is type-safe
and it can be used with wide variety of elements.
169. What is the difference between
Collections.emptyList() and creating
new instance of Collection?
In both the approaches, we get an empty list. But
Collections.emptyList() returns an Immutable list. We cannot add
new elements to an Immutable empty list.
Collections.emptyList() works like Singleton pattern. It does not
create a new instance of List. It reuses an existing empty list
instance.
Therefore, Collections.emptylist() gives better performance if we
need to get an emptyList multiple times.
170. How will you copy elements from
a Source List to another list?
There are two options to copy a Source List to another list.
Option 1: Use ArrayList constructor
ArrayList<Integer> newList = new ArrayList<Integer>(sourceList);
Option 2: Use Collection.copy()
To use Collections.copy() destination list should be of same or
larger size than source list.
ArrayList<Integer> newList = new ArrayList<Integer>
(sourceList.size());
Collections.copy(newList, sourceList);
Collections.copy() does not reallocate the capacity of destination
List if it does not have enough space to contain all elements of
source List. It throws IndexOutOfBoundsException.
The benefit of Collection.copy() is that it guarantees that the copy
will happen in linear time. It is also good for the scenario when we
want to reuse an array instead of allocating more memory in the
constructor of ArrayList.
One limitation of Collections.copy() is that it can accept only List
as source and destination parameters.
171. What are the Java Collection
classes that implement List interface?
Java classes that implement List interface are:
AbstractList
AbstractSequentialList
ArrayList
AttributeList
CopyOnWriteArrayList
LinkedList
RoleList
RoleUnresolvedList
Stack
Vector
172. What are the Java Collection
classes that implement Set interface?
Java classes that implement Set interface are:
AbstractSet
ConcurrentSkipListSet
CopyOnWriteArraySet
EnumSet
HashSet
JobStateReasons
LinkedHashSet
TreeSet
173. What is the difference between an
Iterator and ListIterator in Java?
Iterator and ListIterator are two interfaces in Java to traverse data
structures. The differences between these two are:
1. ListIterator can be used to traverse only a List. But Iterator
can be used to traverse List, Set, and Queue etc.
2. An Iterator traverses the elements in one direction only. It
just goes. ListIterator can traverse the elements in two
directions i.e. backward as well as forward directions.
3. Iterator cannot provide us index of an element in the Data
Structure. ListIterator provides us methods like nextIndex()
and previousIndex() to get the index of an element during
traversal.
4. Iterator does not allow us to add an element to collection
while traversing it. It throws
ConcurrentModificationException. ListIterator allows use
to add an element at any point of time while traversing a
list.
5. An existing element’s value cannot be replaced by using
Iterator. ListIterator provides the method set(e) to replace
the value of last element returned by next() or previous()
methods.
174. What is the difference between
Iterator and Enumeration?
Both Iterator and Enumeration are interfaces in Java to access Data
Structures. The main differences between these are:
1. Enumeration is an older interface. Iterator is a newer
interface.
2. Enumeration can only traverse legacy collections. Iterator
can traverse both legacy as well as newer collections.
3. Enumeration does not provide remove() method. So we
cannot remove any element during traversal. Iterator
provides remove() method.
4. Iterator is a fail-fast interface, it gives
ConcurrentModificationException if any thread tries to
modify an element in the collection being iterated.
Enumeration is not fail-fast.
5. Method names in Iterator are shorter than in an
Enumeration.
175. What is the difference between an
ArrayList and a LinkedList data
structure?
Main differences between ArrayList and LinkedList data structures
are:
1. Data Structure: An ArrayList is an indexed based
dynamic array. A LinkedList is a Doubly Linked List data
structure.
2. Insertion: It is easier to insert new elements in a
LinkedList, since there is no need to resize an array.
Insertion in ArrayList is O(n), since it may require resizing
of array and copying its contents to new array.
3. Remove elements: LinkedList has better performance in
removal of elements than ArrayList.
4. Memory Usage: LinkedList uses more memory than
ArrayList, since it has to maintain links for next and
previous nodes as well.
5. Access: LinkedList is slower in accessing an element,
since we have to traverse the list one by one to access the
right location.
176. What is the difference between a
Set and a Map in Java?
Main differences between a Set and a Map in Java are:
1. Duplicate Elements: A Set does not allow inserting
duplicate elements. A Map does not allow using duplicate
keys, but it allows inserting duplicate values for unique
keys.
2. Null values: A Set allows inserting maximum one null
value. In a Map we can have single null key at most and
any number of null values.
3. Ordering: A Set does not maintain any order of elements.
Some of sub-classes of a Set can sort the elements in an
order like LinkedHashSet. A Map does not maintain any
order of its elements. Some of its sub-classes like
TreeMap store elements of the map in ascending order of
keys.
177. What is the use of a Dictionary
class?
The Dictionary class in Java is used to store key-value pairs. Any
non-null object can be used for key or value. But we cannot insert a
null key or null object in Dictionary.
Dictionary class is deprecated now. So it should not be used in
newer implementations.
178. What is the default size of load
factor in a HashMap collection in
Java?
Default value of load factor in a HashMap is 0.75.
179. What is the significance of load
factor in a HashMap in Java?
A HashMap in Java has default initial capacity 16 and the load
factor is 0.75f (i.e. 75% of current map size). The load factor of a
HashMap is the level at which its capacity should be doubled.
For example, in a HashMap of capacity 16 and load factor .75. The
capacity will become 32 when the HashMap is 75% full. Therefore,
after storing the 12th key– value pair (16 * .75 = 12) into HashMap,
its capacity becomes 32.
180. What are the major differences
between a HashSet and a HashMap?
The main difference between a HashSet and a HashMap are:
1. Base class: A HashSet class implements the Set interface.
Whereas a HashMap class implements the Map interface.
2. Storage: A HashSet is used to store distinct objects. A
HashMap is used for storing key & value pairs, so that
these can be retrieved by key later on.
3. Duplicate Elements: A HashSet does not allow storing
duplicate elements. A HashMap also does not allow
duplicate keys. But we can store duplicate values in a
HashMap.
4. Null Elements: In a HashSet we can store a single null
value. In a HashMap we can store single null key, but any
number of null values.
5. Element Type: A HashSet contains only values of objects
as its elements. Whereas a HashMap contains entries(key
value pairs).
6. Iteration: By using an Iterator we can iterate a HashSet.
But a HashMap has to be converted into Set for iteration.
181. What are the similarities between
a HashSet and a HashMap in Java?
As the name suggests, HashSet and HashMap are Hashing based
collections. Similarities between HashSet and HashMap are:
1. Thread Safety: Both HashMap and HashSet are not
synchronized collections. Therefore they are not good for
thread-safe operations. To make these thread-safe we need
to explicitly use synchronized versions.
2. Order of Elements: None of these classes guarantee the
order of elements. These are unordered collections.
3. Internal Implementation: A HashMap backs up a HashSet
internally. So HashSet uses a HashMap for performing its
operations.
4. Performance: Both of these collections provide constant
time performance for basic operations such as insertion
and removal of elements.
182. What is the reason for
overriding equals() method?
The equals() method in Object class is used to check whether two
objects are same or not. If we want a custom implementation we can
override this method.
For example, a Person class has first name, last name and age. If we
want two Person objects to be equal based on name and age, then
we can override equals() method to compare the first name, last
name and age of Person objects.
Generally in HashMap implementation, if we want to use an object
as key, then we override equals() method.
183. How can we synchronize the
elements of a List, a Set or a Map?
Sometimes we need to make collections Thread-safe for use in
Multi-threading environment. In Java, Collections class provides
useful static methods to make a List, Set or Map as synchronized
collections. Some of these methods are:
static <T> Collection<T> synchronizedCollection(Collection<T>
c)
Returns a synchronized (thread-safe) collection backed by the
specified collection.
static <T> List<T> synchronizedList(List<T> list)
Returns a synchronized (thread-safe) list backed by the specified
list.
static <K,V> Map<K,V>synchronizedMap(Map<K,V> m)
Returns a synchronized (thread-safe) map backed by the specified
map.
static <T> Set<T> synchronizedSet(Set<T> s)
Returns a synchronized (thread-safe) set backed by the specified
set.
static <K,V>
SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m)
Returns a synchronized (thread-safe) sorted map backed by the
specified sorted map.
static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s)
Returns a synchronized (thread-safe) sorted set backed by the
specified sorted set.
184. What is Hash Collision? How
Java handles hash-collision in
HashMap?
In a Hashing scenario, at times two different objects may have same
HashCode but they may not be equal. Therefore, Java will face
issue while storing the two different objects with same HashCode in
a HashMap. This kind of situation is Hash Collision.
There are different techniques of resolving or avoiding Hash
Collision. But in HashMap, Java simply replaces the Object at old
Key with new Object in case of Hash Collision.
185. What are the Hash Collision
resolution techniques?
To resolve a Hash Collision we can use one of the following
techniques:
Separate Chaining with Linked List
Separate Chaining with List Head Cells
Open Addressing with Coalesced Hashing
Open Addressing with Cuckoo Hashing
Hopscotch Hashing
Robinhood Hashing
186. What is the difference between
Queue and Stack data structures?
Queue is a FIFO data structure. FIFO stands for First In First Out. It
means the element added first will be removed first from the queue.
A real world example of Queue is a line for buying tickets at a
station. The person entering first in the Queue is served first.
Stack is a LIFO data structure. LIFO stands for Last In First Out.
The element that is added last is removed first from the collection.
In a Stack elements are added or removed from the top of stack.
A real world example of Stack is back button in browser. We can go
back one by one only and it works in the reverse order of adding
webpages to history .
187. What is an Iterator in Java?
Iterator is an interface in Java to access the elements in a collection.
It is in java.util package.
It provides methods to iterate over a Collection class in Java.
Iterator interface in Java is based on Iterator design pattern. By
using an Iterator one can traverse a container of objects and can
also access the objects in the container. A container of objects is a
Collection class in Java.
188. What is the difference between
Iterator and Enumeration in Java?
Main differences between Iterator and Enumeration in Java are:
1. Version: Enumeration interface is in Java since JDK 1.0.
Iterator interface was introduced in Java 1.2.
2. remove() method: The main difference between
Enumeration and Iterator interface is remove() method.
Enumeration can just traverse a Collection object. If we
use Enumeration, we cannot do any modifications to a
Collection while traversing the collection. Iterator
interface provides remove() method to remove an element
while traversing the Collection. There is not remove()
method in Enumeration interface.
3. Method names: Names of methods in Iterator interface are
hasNext(), next(), remove(). Names of methods in
Enumeration interface are hasMoreElements(),
nextElement().
4. Legacy Interface: Enumeration is considered as a legacy
interface. It is used to traverse legacy classes like Vector,
Stack and HashTable. Iterator is a newer interface that is
used to traverse almost all of the classes in Java
Collections framework.
5. Fail-fast vs. Fail-safe: Iterator is based on fail-fast
principle. It throws ConcurrentModificationException if a
collection is modified during iteration over that collection.
An Enumeration is based on fail-safe principle. It doesn’t
throw any exception if a collection is modified during
traversal.
6. Safety: Since Iterator is fail-fast and does not allow
modification of a collection by other threads, it is
considered safer than Enumeration.
189. What is the design pattern
used in the implementation of
Enumeration in Java?
Enumeration is based on Iterator design pattern. Iterator design
pattern provides a common interface with methods to traverse the
collection of objects. It hides the underlying implementation details
of the collection.
190. Which methods do we need to
override to use an object as key in a
HashMap?
If we want to use an object as a key in a HashMap in Java, then we
have to make sure that it has the implementation of equals() and
hashCode() methods.
191. How will you reverse a List in
Java?
In Collections class, Java provides a method reverse(List list) that
can be used to reverse a List.
E.g.
Collections.reverse(myList);
192. How will you convert an array of
String objects into a List?
Java provides Arrays class in java.util package. Arrays class has a
method asList() that accepts an Array as input and returns a List as
output.
public static <T> List<T> asList(T... a)
String[] myArray = {"George" , "Jack" , "Ryan"};
List myList = Arrays.asList(myArray);
193. What is the difference between
peek(), poll() and remove() methods of
Queue interface in java?
In a Java Queue, poll() and remove() methods can be used for
removing the head object of Queue. The main difference arises in
the case when Queue is empty().
If Queue is empty then poll() method returns null value. If Queue is
empty then remove() method throws NoSuchElementException.
In a Java Queue, peek() method retrieves the head of Queue but it
does not remove it. If queue is empty then peek() method returns
null value.
194. What is the difference between
Array and ArrayList in Java?
The main differences between Array and ArrayList in Java are:
1. Size: Array in Java is fixed in size. We cannot change the
size of array after creating it. ArrayList is dynamic in size.
When we add elements to an ArrayList, its capacity
increases automatically.
2. Performance: In Java Array and ArrayList give different
performance for different operations.
3. add() or get(): Adding an element to or retrieving an
element from an array or ArrayList object has similar
performance. These are constant time operations.
4. resize(): Automatic resize of ArrayList slows down the
performance. ArrayList is internally backed by an Array.
In resize() a temporary array is used to copy elements from
old array to new array.
5. Primitives: Array can contain both primitive data types as
well as objects. But ArrayList cannot contain primitive
data types. It contains only objects.
6. Iterator: In an ArrayList we use an Iterator object to
traverse the elements. We use for loop for iterating
elements in an array.
7. Type Safety: Java helps in ensuring Type Safety of
elements in an ArrayList by using Generics. An Array can
contain objects of same type of class. If we try to store a
different data type object in an Array then it throws
ArrayStoreException.
8. Length: Size of ArrayList can be obtained by using size()
method. Every array object has length variable that is same
as the length/size of the array.
9. Adding elements: In an ArrayList we can use add()
method to add objects. In an Array assignment operator is
used for adding elements.
10. Multi-dimension: An Array can be multi-dimensional. An
ArrayList is always of single dimension.
195. How will you insert, delete and
retrieve elements from a HashMap
collection in Java?
We use following methods to insert, delete and retrieve elements in
a HashMap.
1. Retrieve: We use get() method to retrieve elements from a
HashMap.
Value get(Object key)
2. Insert: We use put() method to insert a key value pair in a
HashMap.
Value put(Key k, Value v)
3. Delete: We use remove() method to delete key-value pair
from the HashMap.
Value remove(Object key)
196. What are the main differences
between HashMap and
ConcurrentHashMap in Java?
Main differences between HashMap and ConcurrentHashMap are:
1. Synchronization: A HashMap is not synchronized. But a
ConcurrentHashMap is a synchronized object.
2. Null Key: A HashMap can have one null key and any
number of null values. A ConcurrentHashMap cannot have
null keys or null values.
3. Multi-threading: A ConcurrentHashMap works well in a
multi-threading environment.
197. What is the increasing order of
performance for following collection
classes in Java?
The increasing order of performance is:
Hashtable
Collections.SynchronizedMap
ConcurrentHashMap
HashMap
Hashtable has the worst performance and HashMap has the best
performance.
198. Why does Map interface not
extend Collection interface in Java?
A Map is a collection objects. But Map interface is not compatible
with Collection interface in Java.
A Map requires key as well as a value. So it requires two
parameters to add an element to a HashMap.
But Collection interface provides add(Object o) method with only
one parameter.
Map collection has to provide methods like valueSet, keySet etc.
These methods are specific to Map collection. Where as methods in
Collection interface can be reused by a List, Set, Queue etc.
199. What are the different ways to
iterate elements of a list in Java?
There are mainly two ways to iterate the elements of list in Java:
1. Iterator: We can get an Iterator for list and use it to iterate
the objects of the list.
2. For-each loop: We can use for-each loop to traverse all
the elements of a list.

Comments
Post a Comment