Skip to main content

Java Collection Interview Questions part- 2


Java Collection



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

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

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

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

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

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

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

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

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

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

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

12.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);


13.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);

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

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

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

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

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

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

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

21. What is CopyOnWriteArrayList? How it is different from ArrayList in Java?

CopyOnWriteArrayList was introduced in Java 5 version. It is a thread-safe collection. It is similar to an ArrayList. In CopyOnWriteArrayList, all mutative operations (add, set etc.) are implemented by making a fresh copy of the underlying array. Iterator of CopyOnWriteArrayList is guaranteed to not throw ConcurrentModificationException. But Iterator also does not reflect any additions, removals that happened to list after the Iterator was created. All elements including null are permitted in CopyOnWriteArrayList.

22.How remove() method is implemented in a HashMap?

Remove() method in HashMap uses logic similar to the one used in get() method. First we locate the correct bucket in HashMap for an entry. Then within that bucket we remove the element e. It is similar to removing a node from a single-linked list. If e is the first element in the bucket we set the corresponding element of Hash to e.next. Else we set the next field of the element just before e to e.next.

23. What is BlockingQueue in Java Collections?

BlockingQueue was introduced in Java 1.5. It extends Queue  interface in Java. BlockingQueue supports operations that wait for the queue to become non-empty when retrieving an element. Also it supports the operations that wait for space to become available in the queue while storing an element.
Some of the features of BlockingQueue are:
It does not accept null elements. Its main use is in producer-consumer  problems. BlockingQueue implementation is thread-safe. It can be used in inter-thread communications. It does not support any kind of "close" or "shutdown" operation to indicate that no more items will be added.

24. How is TreeMap class implemented in Java?

Internally, a TreeMap class in Java uses Red-Black tree. It is a NavigableMap. The map sorts the keys in natural order or it can use a Comparator supplied at the creation time. The implementation of TreeMap is not synchronized in Java.

25. What is the difference between Fail-fast and Fail-safe iterator in Java?

Differences between Fail-fast and Fail-safe iterators are as follows:
Fail-fast iterator throws ConcurrentModificationException. But Fail-safe iterator does not throw this exception. Fail-fast iterator does not clone the original collection. Fail-safe iterator creates a copy of the original collection of objects. A Fail-fast iterator tries to immediately throw Exception when it encounters failure. A Fail-safe Iterator works on a copy of collection instead of original collection.

26. How does ConcurrentHashMap work in Java?

ConcurrentHashMap extends AbstractMap in Java. It was introduced in Java 1.5. It provides concurrency in a collection based on a HashMap. All methods are thread-safe in ConcurrentHashMap. Internally there is a Hashtable backing a ConcurrentHashMap. This Hashtable supports the concurrent methods for retrieval of data as well as updates on ConcurrentHashMap. It has same functional specification as a Hashtable. It also supports a set of sequential and bulk operations. These operations accept parallelismThreshold argument.

27. What is the importance of hashCode() and equals() methods?

In a HashMap collection it is very important for a key object to implement hashCode() method and equals() method. If hashCode() method returns same hashcode for all key objects then the hash collision will be high in HashMap. Also with same hashcode, we will get same equals method that will make our HashMap inefficient. The problem arises when HashMap treats both outputs same instead of different. It will overwrite the most recent key-value pair with the previous key-value pair. So it is important to implement hashCode() and equals() methods correctly for an efficient HashMap collection.

28. What is the contract of hashCode() and equals() methods in Java?

Contract of hashCode() and equals() methods is as follows in Java:
If object1.equals(object2), then object1.hashCode() == object2.hashCode() should always be true. It means if two objects are equal then their hashCode should be same. If object1.hashCode() == object2.hashCode() is true, it does not guarantee that object1.equals(object2). It means if two objects have same hashCode, then can still have different values so that may not be equal objects.

29. What is an EnumSet in Java?

1.     Set: EnumSet is a specialized implementation of Set.
2.     Use: It is mainly used with enum types.
3.     Single enum type: All the elements in an EnumSet must come from a single enum type when the set is created.
4.     Bit vector: Internally, EnumSet is represented as bit vector.
5.     Iterator: The iterator of EnumSet traverses the elements in their natural order. (It is the order in which the enum constants are declared).
6.     Null: In an EnumSet, null elements are not permitted. If we try to insert a null element it throws NullPointerException.
7.     Thread-safe: EnumSet is not a synchronized collection. For use in multi-threading scenarios, EnumSet should be synchronized.
8.     Bit flags: EnumSet is a very good alternative to int based “bit flags” implementation.

30. What are the main Concurrent Collection classes in Java?

Java 1.5 has provided new package java.util.concurrent. This package contains thread-safe collection classed. These collection classes can be modified while iterating. The iterator of these classes is fail-safe.
Main Concurrent Collection classes in Java 8 are:
·        ArrayBlockingQueue
·        CopyOnWriteArrayList
·        CopyOnWriteArraySet
·        ConcurrentHashMap
·        ConcurrentLinkedDeque
·        ConcurrentLinkedQueue
·        LinkedBlockingQueue
·        LinkedBlockingDeque
·        PriorityBlockingQueue

31.How will you convert a Collection to SynchronizedCollection in Java?

Java provides an easy method in java.utils.Collections class to create a ThreadSafe collection from a regular collection. We can use the method synchronizedCollection() for this purpose. For any class of type T we can use following method:
static <T> Collection<T> synchronizedCollection(Collection<T> c)

32.How IdentityHashMap is different from a regular Map in Java?

IndentityHashMap in Java implements Map interface. But it is not a general purpose implementation. It violates the general contract of Map interface by a different implementation of equals() method. In an IdentityHashMap, two keys k1 and k2 are equal if and only if (k1==k2). (In a normal Map implementation (like HashMap) two keys k1 and k2 are considered equal if and only if (k1==null ? k2==null : k1.equals(k2)).) It implements the Map interface with a hash table, using referenceequality in place of object-equality when comparing keys (and values).

33.What is the main use of IdentityHashMap?

Main uses of IdentityHashMap are:
1.     Topology Preservation: The typical use of IdentityHashMap class is topology-preserving object graph transformations, such as serialization or deepcopying. In such a scenario, a program must maintain a "node table" to keep track of all the object references that have already been processed.  
2.     The node table should not considered distinct objects as equal even if they happen to be equal.
3.     Proxy objects: Another use of this class is to maintain proxy objects. A debugging program has to maintain a proxy object for each object in the program being debugged.

34.How can we improve the performance of IdentityHashMap?

IdentityHashMap class has one tuning parameter for performance  improvement:
expectedMaxSize. This parameter is the maximum number of key-value mappings that the map is expected to hold. We can use this parameter is used to determine the number of buckets initially in the hash table. The precise relationship between the expected maximum size and the number of buckets is unspecified. If the number of key-value mappings exceeds the expected maximum size, the number of buckets is increased. Increasing the number of buckets is also known as rehashing. Rehashing may be fairly expensive. So it is better to create identity hash maps with a sufficiently large expected maximum size. But iteration over a Map collection requires time proportional to the number of buckets in the hash table. So iteration may take extra time due to large number of buckets. Therefore the value of expectedMaxSize should be set in consideration with both of these aspects.

35. Is IdentityHashMap threadsafe?

The implementation of IdentityHashMap is not thread-safe, since its methods are not synchronized. The iterators returned by the iterator method of IdentityHashMap are fail-fast. But the fail-fast behavior of an iterator cannot be guaranteed. Since the Iterator is fail-fast, it throws ConcurrentModificationException.

36.What is a WeakHashMap in Java?

WeakHashMap is a class similar to IdentityHashMap. Internally, it is represented by a Hashtable. It is not a synchronized class. We can make a WeakHashMap thread safe by using Collections.synchronizedMap() method. An entry in WeakHashMap is automatically removed when it is no longer in ordinary use. The presence of a mapping for a given key does not prevent the key from being discarded by the garbage collector. WeakHashMap also permits null keys and null values.

37.How can you make a Collection class read Only in Java?

In Java, there are useful methods to make a Collection class read Only. We can make the Collection read Only by using one of the following methods:
Collections.unmodifiableMap(Map m)
Collections.unmodifiableList(List l)
Collections.unmodifiableSet(Set s)
Collections.unmodifiableCollection(Collection c)

38.When is UnsupportedOperationException thrown in Java?

In a Java collection UnsupportedOperationException is thrown when the requested operation is not supported by the collection. It is an unchecked exception that is thrown on optional operations. If there is an optional add() or remove() methods in a read only collection, then this exception can be thrown.

39.What is the difference between Synchronized Collection and Concurrent Collection?

In Java 1.5 many Concurrent collection classes were added in SDK. These are ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue etc. Java also provides utility methods to get a synchronized copy of collection like ArrayList, HashMap etc. by using  Collections.synchronizedList(), Collections.synchronizedMap() methods. The main difference is in performance. Concurrent collection classes have better performance than synchronized collection classes because they lock only a portion of the class to achieve concurrency and thread-safety.

40. What is the scenario to use ConcurrentHashMap in Java?

ConcurrentHashMap is more suited for scenarios where we have multiple reader threads and one writer thread. In this case map is locked only during the write operation. If we have an equal number of reader and writer threads then ConcurrentHashMap performance is similar to a Hashtable or a synchronized HashMap.

41.How will you create an empty Map in Java?

There are two ways to create an empty Map in Java.
1.     Immutable: If we want an immutable empty Map, we can use following code:
myMap = Collections.emptyMap();
2.     Any map: For all other scenarios, we can use following code by using new method:
myMap = new HashMap();

42. What is the difference between remove() method of Collection and remove() method of Iterator?

In Collection interface remove(Object o) method is used to remove objects from a Collection. List interface also provides remove(int index) method to remove an object at a specific index. These methods are used to remove an entry from Collection, while no thread is iterating over it. When we are iterating over a Collection, then we have to remove() method of Iterator. This method removes current element from Iterator’s point of view. If we use remove(0 method of Collection or List, then we will get ConcurrentModificationException. Therefore, it is recommended to use remove() method of Iterator during the traversal of a Collection by an Iterator.

43. Between an Array and ArrayList, which one is the preferred collection for storing objects?

An ArrayList is backed up by array internally. There are many usability advantages of using an ArrayList over an array in Java. Array has a fixed length at the time of creation. Once it is created we cannot change its length. ArrayList is dynamic in size. Once it reaches a threshold, it automatically allocates a new array and copies contents of old array to new array. Also ArrayList provides support of Generics. But Array does not support Generics. E.g. If we store an Integer object in a String array at Runtime it will throw ArrayStoreException. Whereas, if we use ArrayList then as compile time we will get the error. This helps in preventing errors from happening at runtime. If we know the size in advance and do not need re-sizing the collection then Array should be used in place of an ArrayList.


44. Is it possible to replace Hashtable with ConcurrentHashMap in Java?

Yes, a ConcurrentHashMap can be replaced with Hashtable in Java. But it requires careful observation, since locking behavior of Hashtable is different than that of ConcurrentHashmap. A Hashtable locks whole Map instead of a portion of Map. Compound operations like if(Hashtable.get(key) == null) put(key, value) work in Hashtable but not in ConcurrentHashMap. In a ConcurrentHashMap we use putIfAbsent() method for such a scenario.

45. How CopyOnWriteArrayList class is different from ArrayList and Vector classes?

CopyOnWriteArrayList was introduced in Java 1.5. It implements List interface. It provides better concurrent access methods than a Synchronized List. In CopyOnWriteList, concurrency is achieved by copying ArrayList over each write and replace with original instead of locking. CopyOnWriteArrayList also does not throw any ConcurrentModification Exception during Iteration. It is a thread-safe list. It is different from a Vector in terms of Concurrency. CopyOnWriteArrayList provides better Concurrency by reducing contention among readers and writers.

46. Why ListIterator has add() method but Iterator does not have?

ListIterator can iterate in the both directions of a Collection. It maintains two pointer for previous and next element. In ListIterator we can use add() method to add an element into the list immediately before the element returned by next() method. So a subsequent call to next() method will not be affected. And the call to previous() method will return the newly added element. In Iterator we can only traverse in one direction. So there is no purpose of add() method there.

47. Why do we sometime get ConcurrentModificationException during iteration?

When we remove an object by using remove() method of a  Collection or List while an Iterator thread is traversing it, we get ConcurrentModificationException. If an Iterator detects any structural change in Collection it can throw ConcurrentModificationException.

48. How will you convert a Map to a List in Java?

In Java, a Map has three collection sets:
·        key set
·        value set
·        key-value set
Each of these Sets can be converted to List by using a constructor.
Sample code is as follows:
List keyList = new ArrayList(map.keySet());
List valueList = new ArrayList(map.values());
List entryList = new ArrayList(map.entrySet());

49. How can we pass a Collection as an argument to a method and ensure that method will not be able to modify it?

To ensure that a method is not able to modify a Collection passed as an argument, we have to make the Collection read only. We can make a read only collection by using Collections.unmodifiableCollection(Collection c) method. This will make sure that any operation to change the collection will throw UnsupportedOperationException.

50. Can you explain how HashMap works in Java?

In Java, a HashMap works on the concept of hashing. A HashMap in Java stores both key and value objects, in a bucket. It is stored as an Entry object that implements Map.Entry interface. The key object used in a HashMap has to provide implementation for hashCode() and equals() methods. When put() method is used to store a key-value pair, the HashMap implementation calls hashCode() method on Key object to calculate a hash that is used to find a bucket where Entry object will be stored. When get() method is used to retrieve a value stored against a key object, we first calculate a hash of Key object. Then we use this hash to find the bucket in which that particular key is stored. Once Key object’s location is found, it may happen that more than one Key is stored in same location. So now we use equals() method to find the exact Key object. Once the exact Key object is found we use it to get Value object.

51. Can you explain how HashSet is implemented in Java?

Internally, a HashSet uses a HashMap to store the elements and to maintain the uniqueness of elements. When we create a HashSet object, a corresponding HashMap object is also created. When we insert an element in HashSet, it inserts it into corresponding HashMap.

52. What is a NavigableMap in Java?

As the name suggests, NavigableMap provides the capability to navigate the keys of a Map in Java. A NavigableMap extends SortedMap interface. Some of the interesting methods of a NavigableMap are descendingKeySet(), descendingMap(), headMap() and tailMap().

53. What is the difference between descendingKeySet() and descendingMap() methods of NavigableMap?

The descendingKeySet() method of NavigableMap returns a NavigableSet in which the elements are stored in reversed order as compared to the original key set. The returned view is internally represented by the original KeySet of NavigableMap. Therefore any changes to the descending set also get reflected in the original set. But it is not recommended to remove elements directly from the key set. We should use the Map.remove() method. The descendingMap() method of NavigableMap returns a NavigableMap which is an inverse view of the original Map. The order of the elements in this view are in reverse order of the elements in original map. Any changes to this view are also reflected in the original map.

54. Let say there is a Customer  class. We add objects of Customer class to an ArrayList. How can we sort the Customer objects in ArrayList by using customer firstName attribute of Customer class?

There are two ways to handle this scenario.
We can use these options:
1.     Comparable: Implement the Comparable interface for Customer class and compare customer objects by firstName attribute.
2.     Comparator: Implement Comparator for comparing two Customer objects on the basis of firstName attribute. Then use this comparator object in sort method of Collections class.



Comments

Popular posts from this blog

DOCKER Interview questions

DOCKER 1. What is Docker? Docker is Open Source software. It provides the automation of Linux application deployment in a software container. We can do operating system level virtualization on Linux with Docker. Docker can package software in a complete file system that contains software code, runtime environment, system tools, & libraries that are required to install and run the software on a server. 2. What is the difference between Docker image and Docker container? Docker container is simply an instance of Docker image. A Docker image is an immutable file, which is a snapshot of container. We create an image with build command. When we use run command, an Image will produce a container. In programming language, an Image is a Class and a Container is an instance of the class. 3. How will you remove an image from Docker? We can use docker rmi command to delete an image from our local system. Exact command is: % docker rmi <Image Id> If we want to fin

Microservices Interview Questions

Microservices Interview Questions 1. What is a Microservice in Java? A Microservice is a small and autonomous piece of code that does one thing very well. It is focused on doing well one specific task in a big system. It is also an autonomous entity that can be designed, developed and deployed independently. Generally, it is implemented as a REST service on HTTP protocol, with technology-agnostic APIs. Ideally, it does not share database with any other service. 2. What are the benefits of Microservices architecture? Microservices provide many benefits. Some of the key benefits are: 1.      Scaling : Since there are multiple Microservices instead of one monolith, it is easier to scale up the service that is being used more. Eg. Let say, you have a Product Lookup service and Product Buy service. The frequency of Product Lookup is much higher than Product Buy service. In this case, you can just scale up the Product Lookup service to run on powerful hardware with multipl

Cloud Computing Interview Questions

Cloud Computing 1. What are the benefits of Cloud Computing? There are ten main benefits of Cloud Computing: Flexibility : The businesses that have fluctuating bandwidth demands need the flexibility of Cloud Computing. If you need high bandwidth, you can scale up your cloud capacity. When you do not need high bandwidth, you can just scale down. There is no need to be tied into an inflexible fixed capacity infrastructure. Disaster Recovery : Cloud Computing provides robust backup and recovery solutions that are hosted in cloud. Due to this there is no need to spend extra resources on homegrown disaster recovery. It also saves time in setting up disaster recovery. Automatic Software Updates : Most of the Cloud providers give automatic software updates. This reduces the extra task of installing new software version and always catching up with the latest software installs. Low Capital Expenditure : In Cloud computing the model is Pay as you Go. This means there is very