Java Collection
In this Java
Interview Question blog, we have covered almost 25+ important core Java
interview questions and answar for freshers and experienced candidates.
This post on JAVA Collection Interview Questions and Answars is prepared to help you understand the basic concepts of Java programming for top compnyes interview purposes.
Most Popular Java Collection Interview Questions:
Given below is a
comprehensive list of most important and commonly asked basic and advanced Java
programming interview questions with detailed answers.
1. What is the difference between Collection and Collections Framework in Java?
In Java, a Collection is an object that
contains multiple elements of same type in a single unit. These multiple
elements can be accessed through one Collection object. In Java Collections
Framework is a library that provides common architecture for creating, updating
and accessing different types of collections. In Collections framework there
are common methods that are frequently used by developers for working on a
Collection object.
2. What are the main benefits of Collections Framework in Java?
Main benefits of Collections Framework
in Java are as follows:
1.
Reusability: Java Collections Framework provides common classes
and utility methods than can be used with different types of collections. This
promotes the reusability of the code. A developer does not have to re-invent
the wheel by writing the same method again.
2.
Quality: Using Java Collection Framework improves the program
quality, since the code is already tested and used by thousands of developers.
3.
Speed: Most of programmers report that their development
speed increased since they can focus on core logic and use the generic
collections provided by Java framework.
4.
Maintenance: Since most of the Java Collections framework code is
open source and API documents is widely available, it is easy to maintain the
code written with the help of Java Collections framework. One developer can
easily pick the code of previous developer.
3. What is the root interface of Collection hierarchy in Java?
The root interface of Collection
hierarchy in Java is Collection interface. But the Collection interface extends
Iterable interface. Due to this some people consider Iterable interface as the
root interface. Iterable interface is present in java.lang package but
Collection interface is present in java.util package. Oracle Java API docs
mention that Collection interface is a member of the Java Collections
framework. Whereas, Iterable interface is not stated as a part of Java
Collections framework in Java docs. Due to this Collection interface is the
root of Collections Framework.
4. What are the main differences between Collection and Collections?
Main differences between Collection and
Collections are as follows:
1.
Collection is an
interface in Java. But Collections is a class in Java.
2.
Collection is a
base interface. Collections is a utility class in Java.
3.
Collection
defines methods that are used for data structures that contain the objects.
Collections defines the methods that are used for operations like access, find
etc. on a Collection.
5. What are the Thread-safe classes in Java Collections framework?
The Thread-safe classes in Java
Collections framework are:
·
Stack
·
Properties
·
Vector
·
Hashtable
·
BlockingQueue
·
ConcurrentMap
·
ConcurrentNavigableMap
6. How will you efficiently remove elements while iterating a Collection?
The right way to remove elements from a
collection while iterating is by using ListIterator.remove() method. E.g.
ListIterator<Integer> iter = myList.iterator();
while(iter.hasNext()) {
itr.remove();
}
Some developers use following code to
remove an element which is incorrect:
Iterator<Integer> iter = myList.iterator();
while(iter.hasNext()) {
itr.remove();
}
By doing so we get
ConcurrentModificationException.
An iterator is first created to traverse
the list. But at the same time the list is changed by remove() method. In Java,
it is not allowed for a thread to modify a collection while another thread is
iterating it. ListIterator provides the capability of removing an object during
traversal.
7. What is the advantage of NavigableMap over Map?
The main advantage of NavigableMap over
Map is the Navigation capability. It provides the capabilities of a Map,
SortedMap and navigation in one collection. It even returns the closest matches
for given search targets. Methods like lowerEntry, floorEntry, ceilingEntry,
and higherEntry return Map.Entry objects associated with keys respectively less
than, less than or equal, greater than or equal, and greater than a given key.
Methods like lowerKey, floorKey, ceilingKey, and higherKey return only the
associated keys. All of these methods are designed for locating, not traversing
entries.
8. What is the difference between headMap(), tailMap() and subMap() methods of NavigableMap?
The headMap() method returns a view of
the original NavigableMap that contains the elements that are less than a given
element.
NavigableMap original = new TreeMap();
original.put("1", "1");
original.put("2", "2");
original.put("3", "3");
//this headmap1 will contain elements "1"
and "2"
SortedMap headmap1 = original.headMap("3");
//this headmap2 will contain elements "1",
"2", and "3" because "inclusive"=true
NavigableMap headmap2 =
original.headMap("3", true);
The tailMap() method works similar to
headMap() method, but it returns all elements that are higher than the given
input element. The subMap() method accepts two parameters demarcating the
boundaries of the view map to return. All the three methods return a subset of
the original map in a view form.
9. How will you sort objects by Natural order in a Java List?
We can use Collections.sort method to
sort the elements of a List in natural order. To use this method, we have to
make sure that element objects implement compareTo() method. We can also use a
Comparator to define the natural ordering for elements of a List. Then we can
use this Custom Comparator in sort method of Collections class.
10. How can we get a Stream from a List in Java?
From Java 8 onwards it is a very easy to
get a Stream from a List. We can just use stream() method to get a stream from
a list of elements.
11. Can we get a Map from a Stream in Java?
Yes, we can create a Map from the
elements of a Stream. We can use map() method to get a Map.
E.g.
items.stream().map( item -> item.toLowerCase() )
In this example we are creating a map
with each item object mapped to its LowerCase equivalent. This is also used in
Map-Reduce implementation on a Stream.
12. What are the popular implementations of Deque in Java?
The two most popular implementation of
Deque interface in Java are:
1.
ArrayDeque: It is a resizable array implementation of Deque. The
capacity of ArrayDeque can increase based on the need of the program. It is not
thread safe implementation. Also the iterator on ArrayDeque is failfast.
2.
LinkedList: This is another popular implementation of Deque
interface in Java. It is also not synchronized, so it is not thread-safe. It
mainly provides functionality of a doubly linked list.
13.How will you convert a List into an array of integers like- int[]?
We can use ArrayUtils class in Apache
Commons Lang library.
Sample code is:
int[]intArray =
ArrayUtils.toPrimitive(myList.toArray(new Integer[0]));
If we use List.toArray(), it will
convert List to Integer[].
Another option is:
int[] intArray = new int[myList.size()];
for (int i=0; i < myList.size(); i++) {
intArray [i] = myList.get(i);
}
14.How will you convert an array of primitive integers int[] to a List collection?
We can use ArrayUtils in Apache Commons
Lang library for this purpose.
Sample code is:
List intList =
Arrays.asList(ArrayUtils.toObject(intArray));
The other option would be to use a for
loop and explicitly adding integers to a List.
Sample code is:
int[]intArray = {10,20,30};
List<Integer> intList = new
ArrayList<Integer>();
for (int i: intArray) {
intList.add(i);
}
15.How will you run a filter on a Collection?
We can use CollectionUtils of Apache for
this purpose. We will have to create a Predicate that will define the condition
for our filter. Then we can apply this Predicate in filter() method.
Sample code is:
In this example we filter any names that
are less than 5 characters long.
List<String> namesList = asList(
"Red", "Blue", "Green" );
List<String> shortNamesList = new
ArrayList<String>();
shortNamesList.addAll( namesList );
CollectionUtils.filter( shortNamesList, new
Predicate(){
public boolean evaluate( Object input )
{
return ((String) input).length() < 5;
}
} );
We can also use Google Guava library for
this. In Java 8, we can use Predicate to filter a Collection through Stream.
16.How will you convert a List to a Set?
There are two ways to convert a List to
a Set in Java.
Option 1: Use HashSet
Set<Integer> mySet = new
HashSet<Integer>(myList);
In this case we put a list into a
HashSet. Internally hashCode() method is used to identify duplicate elements.
Option 2: Use TreeSet In this case we use our own comparator
to find duplicate objects.
Set<Integer> mySet = new
TreeSet<Integer>(myComparator);
mySet.addAll(myList);
17. How will you remove duplicate elements from an ArrayList?
The trick in this question is to use a
collection that does not allow duplicate elements. So we use a Set for this
purpose.
Option 1: Use Set If ordering of elements is not important
then we just put the elements of ArrayList in a HashSet and then add them back
to the ArrayList.
Sample Code is:
ArrayList myList = // ArrayList with
duplicate elements
Set<Integer> mySet = new
HashSet<Integer>(myList);
myList.clear();
myList.addAll(mySet);
Option 2: Use LinkedHashSet If ordering of elements is
important then we put the elements of ArrayList in a LinkedHashSet and then add
them back to the ArrayList.
Sample Code is:
ArrayList myList = // ArrayList with
duplicate elements
Set<Integer> mySet = new
LinkedHashSet<Integer>(myList);
myList.clear();
myList.addAll(mySet);
18. How can we create a Map with reverse view and lookup in Java?
In a Map we can lookup for a value by
using a distinct key. In a Map with reverse view and lookup, even the values
are distinct. So there is one to one mapping between keys and values and vice
version. If we enable this constraint on a Map then we can look up a key by its
value. Such data structure is called bi-directional map. There is no built data
structure similar to reverse lookup Map in JDK. But Apache Common Collections
and Guava libraries provide implementation of bidirectional map. It is called
BidiMap and BiMap. Both of these data structure enforce the constraint of one
to one mapping between keys and values.
19. How will you create a shallow copy of a Map?
In Java, most implementations of Map
interface provide a constructor to create copy of another map. But the copy
method is not synchronized. Therefore, when a thread is copying the map, another
thread can modify it. To prevent such a scenario, we should use
Collections.synchronizedMap() method to first create a thread-safe map. Another
way of to create a shallow copy is by using clone() method. But it is not
considered as a recommended approach.
20.Why we cannot create a generic array in Java?
Java does not allow creation of array
with generics as elements. In Java an array has to know the type information of
its elements at runtime. This information is used at runtime to throw
ArrayStoreException if data type of an element to be inserted does not match
the type of Array. In case of Generics, the type information of a collection is
erased at runtime by Type Erasure. Due to this array cannot use generics as
elements.
21. What is a PriorityQueue in Java?
A PriorityQueue is data structure based
on Queue. Unlike Queue, the elements on PriorityQueue are not returned in FIFO
order. A PriorityQueue maintains the natural order of its elements or it uses a
Comparator provided at initialization. It is an unbounded queue based on a
priority heap. PriorityQueue does not allow null values. We cannot add any
object that does not provide natural ordering to PriorityQueue. PriorityQueue
in Java is not thread-safe. It gives O(log n) time for enqueing and dequeing
operations.
22. What are the important points to remember while using Java Collections Framework?
Some of the important points to remember
while using Java Collections Framework are:
1.
Interfaces: For Collections, we should write code with generic
interfaces instead of concrete implementation. Due to this we maintain the
flexibility of changing the implementation at a later point of time.
2.
Generics: We should use Generics for type-safety and to avoid
ClassCastException at runtime.
3.
Collections: It is recommended to use Collections utility class
for algorithms and various other common methods for Collections.
4.
Right Type: We have to choose the right type of Java collection
based on our need. If size is fixed, we can use Array over ArrayList. If we do
not want duplicate elements we use Set. If we need the ability to iterate the
elements of a Map in the order of insertion then we use a TreeMap.
5.
Initial Size: In some collection classes we can specify the
initial size/capacity. Therefore we should have an estimate of number of
elements in a Collection before deciding the right collection type. We can use
it to avoid rehashing or resizing.
6.
Map: We should use immutable classes provided by Java as
key elements in a Map.
23.How can you maintain a Collection with elements in Sorted order?
In Java, there are many ways to maintain
a Collection with elements in sorted order. Some collections like TreeSet store
elements in the natural ordering. In case of natural ordering we have to
implement Comparable interface for comparing the elements. We can also maintain
custom ordering by providing a custom Comparator to a Collection. Another
option is to use the utility method Collections.sort() to sort a List. This
sorting gives nlog(n) order of performance. But if we have to use this method
multiple times then it will be costly on performance. Another option is to use
a PriorityQueue that provides an ordered queue. The main difference between
PriorityQueue and Collections.sort() is that PriorityQueue maintains a queue in
Order all the time, but we can only retrieve head element from queue. We cannot
access the elements of PriorityQueue in Random order. We can use TreeSet to
maintain sorted order of elements in collection if there are no duplicate
elements in collection.
24.What are the differences between the two data structures: a Vector and an ArrayList?
An ArrayList is a newer class than a
Vector. A Vector is considered a legacy class in Java. The differences are:
1.
Synchronization: Vector is synchronized, but the ArrayList is not
synchronized. So an ArrayList has faster operations than a Vector.
2.
Data Growth: Internally both an ArrayList and Vector use an array
to store data. When an ArrayList is almost full it increases its size by 50% of
the array size. Whereas a Vector increases it by doubling the underlying array size.
25.What are the differences between Collection and Collections in Java?
Main differences between Collection and
Collections are:
1.
Type: Collection is an interface in Java. Collections is a
class.
2.
Features: Collection interface provides basic features of data
structure to List, Set and Queue interfaces. Collections is a utility class to
sort and synchronize collection elements. It has polymorphic algorithms to
operate on collections.
3.
Method Type: Most of the methods in Collection are at instance
level. Collections class has mainly static methods that can work on an instance
of Collection.
26. In which scenario, LinkedList is better than ArrayList in Java?
ArrayList is more popular than
LinkedList in Java due to its ease of use and random access to elements
feature. But LinkedList is better in the scenario when we do not need random
access to elements or there are a lot of insertion, deletion of elements.
27.What are the differences between a List and Set collection in Java?
Main differences between a List and a
Set are:
1.
Order: List collection is an ordered sequence of elements.
A Set is just a distinct collection of elements that is unordered.
2.
Positional
Access: When we use a List, we can
specify where exactly we want to insert an element. In a Set there is no order,
so we can insert element anywhere without worrying about order.
3.
Duplicate: In a List we can store duplicate elements. A Set can
hold only unique elements.
28.What are the differences between a HashSet and TreeSet collection in Java?
Main differences between a HashSet and
TreeSet are:
1.
Ordering: In a HashSet elements are stored in a random order.
In a TreeSet, elements are stored according to natural ordering.
2.
Null Value
Element: We can store null value
object in a HashSet. A TreeSet does not allow to add a null value object.
3.
Performance: HashSet performs basic operations like add(),
remove(), contains(), size() etc in a constant size time. A TreeSet performs
these operations at the order of log(n) time.
4.
Speed: A HashSet is better than a TreeSet in performance
for most of operations like add(), remove(), contains(), size() etc .
5.
Internal
Structure: a HashMap in Java
internally backs a HashSet. A NavigableMap backs a TreeSet internally.
6.
Features: A TreeSet has more features compared to a HashSet.
It has methods like pollFirst(), pollLast(), first(), last(), ceiling(),
lower() etc.
7.
Element
Comparison: A HashSet uses equals()
method for comparison. A TreeSet uses compareTo() method for comparison to
maintain ordering of elements.
29. In Java, how will you decide when to use a List, Set or a Map collection?
1.
If we want a
Collection that does not store duplicate values, then we use a Set based collection.
2.
If we want to
frequently access elements operations based on an index value then we use a
List based collection. E.g. ArrayList
3.
If we want to
maintain the insertion order of elements in a collection then we use a List
based collection.
4.
For fast search
operation based on a key, value pair, we use a HashMap based collection.
5.
If we want to
maintain the elements in a sorted order, then we use a TreeSet based
collection.
30.What are the differences between a HashMap and a Hashtable in Java?
Main differences between a HashMap and a
Hashtable are:
1.
Synchronization: HashMap is not a synchronized collection. If it is
used in multi-thread environment, it may not provide thread safety. A Hashtable
is a synchronized collection. Not more than one thread can access a Hashtable
at a given moment of time. The thread that works on Hashtable acquires a lock
on it and it makes other threads wait till its work is completed.
2.
Null values: A HashMap allows only one null key and any number of
null values. A Hashtable does not allow null keys and null values.
3.
Ordering: A HashMap implementation by LinkedHashMap maintains
the insertion order of elements. A TreeMap sorts the mappings based on the
ascending order of keys. On the other hand, a Hashtable does not provide
guarantee of any kind of order of elements. It does not maintain the mappings
of key values in any specific order.
4.
Legacy: Hashtable was not the initial part of collection
framework in Java. It has been made a collection framework member, after being
retrofitted to implement the Map interface. A HashMap implements Map interface
and is a part of collection framework since the beginning.
5.
Iterator: The Iterator of HashMap is a fail-fast and it throws
ConcurrentModificationException if any other Thread modifies the map by
inserting or removing any element except iterator’s own remove() method.
Enumerator of the Hashtable is not fail-fast.
31. 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.
32.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.
33.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.
34.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.
35.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.
36.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.
37.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.
38. 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
39.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
40.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.
41. 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.
42.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.
43.What is the difference between a Set and a Map in Java?
Main differences between a Set and a Map
in Java are:
1.
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.
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.
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.
44.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.
45.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.
46.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.
47.What are the differences between a HashMap and a TreeMap?
Main differences between a HashMap and a
TreeMap in Java are:
1.
Order: A HashMap does not maintain any order of its keys.
In a HashMap there is no guarantee that the element inserted first will be
retrieved first.
2.
In a TreeMap
elements are stored according to natural ordering of elements. A TreeMap uses
compareTo() method to store elements in a natural order.
3.
Internal
Implementation: A HashMap uses
Hashing internally. A TreeMap internally uses Red-Black tree implementation.
4.
Parent
Interfaces: A HashMap implements Map
interface. TreeMap implements NavigableMap interface.
5.
Null values: A HashMap can store one null key and multiple null
values. A TreeMap can not contain null key but it may contain multiple null
values.
6.
Performance: A HashMap gives constant time performance for
operations like get() and put(). A TreeMap gives order of log(n) time
performance for get() and put() methods.
7.
Comparison: A HashMap uses equals() method to compare keys. A
TreeMap uses compareTo() method for maintaining natural ordering.
8. Features: A TreeMap has more features than a HashMap. It has methods like pollFirstEntry() , pollLastEntry() , tailMap() , firstKey() , lastKey() etc. that are not provided by a HashMap.
Comments