Last Updated on July 9, 2023 by KnownSense
1. What is java Collection framework and mention some benefits of it.
Java 1.2 came up with Collections Framework that group all the collections interfaces, implementations and algorithms. Java Collections have come through a long way with the usage of Generics and Concurrent Collection classes for thread-safe operations. It also includes blocking interfaces and their implementations in java concurrent package. Some of the benefits of collections framework are;
- Reduced development effort by using core collection classes rather than implementing our own collection classes.
- Code quality is enhanced with the use of well tested collections framework classes.
- Reduced effort for code maintenance by using collection classes shipped with JDK.
- Reusability and Interoperability
2. What is the use of Generics in Collections?
Generics allow us to provide the type of Object that a collection can contain, so if you try to add any element of other type it throws compile time error. This avoids ClassCastException at Runtime because you will get the error at compilation. Also Generics make code clean since we don’t need to use casting and instanceof operator.
3. What re the basic Interfaces of java Collections framework?
1. Set
- Set is a collection, which avoids containing duplicate elements.
- This interface models the mathematical set abstraction and is used to represent sets, such as the deck of cards.
- Set doesn’t maintain the order.
- HashSet, LinkedHashSet or TreeSet are the implementations of the Set interface.
- Set also adds a stronger contract on the behaviour of the equals and hashCode
- Code Snippet: Set set = new HashSet();
2. List
- The list follows the ordered collection and can contain duplicate elements.
- One can access any element from its index.
- The list is somewhat like array however length is changing at runtime.
- List interface doesn’t provide the thread safety.
- ArrayList, LinkedList, CopyOnWriteArray are the implementation of List interface.
- Code Snippet: List list = new ArrayList();
3. Queue
- Queue interface is a part of collection framework extend the collection interface.
- A queue is used to insert elements at the end of the queue and removes from the beginning of the queue. It based on the FIFO concept.
- The queue is inherited from the Collection framework, so it supports all the method like insertion and deletion.
- ArrayBlockingqueue and PriorityQueue are the most widely used implementation classes.
- public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable
- Code Snippet: Queue queue = new PriorityQueue();
4. What is a Map Interface and why it is not a part of Collection framework?
A map is an object that maps keys to values. The map works on key-value pair principal. A map doesn’t allow to contain duplicate keys. Each key can map to at most one value. HashMap, TreeMap, ConcurentHashMap are the implementation of the map. The map has three kind of collection like key, values and key values and it doesn’t implement the collection interface that is the reason the Map interface doesn’t fall in the collection hierarchy. The order of the map depends on the specific implementation classes.
Map map = new HashMap();.
The best use case is when we need to specify the pairing between the object and store accordingly.
5. Differentiate between Collections and Collection in java?
Collection : In the java.util.package, there is an interface called a collection. It’s used to represent a collection of separate objects as a single entity. It’s equivalent to the container in the C++ programming language. The collection framework’s root interface is referred to as the collection. It has a number of classes and interfaces for representing a collection of individual objects as a single unit. The key sub-interfaces of the collection interface are List, Set, and Queue. Although the map interface is part of the Java collection framework, it does not inherit the interface’s collection. The Collection interface’s most significant functions are add(), remove(), clear(), size(), and contains().
Collections: The java.util.package has a utility class called Collections. It defines various utility methods for working with collections, such as sorting and searching. All of the methods are static. These techniques give developers much-needed convenience, allowing them to interact with Collection Framework more successfully. It provides methods like sort() to sort the collection elements in the normal sorting order, and min() and max() to get the minimum and maximum value in the collection elements, respectively.
6. Why Collection doesn’t extend Cloneable and Serializable interface?
Collection interface specifies group of Objects known as elements. How the elements are maintained is left up to the concrete implementations of Collection. For example, some Collection implementations like List allow duplicate elements whereas other implementations like Set don’t. A lot of the Collection implementations have a public clone method. However, it doesn’t make sense to include it in all implementations of Collection. This is because Collection is an abstract representation. What matters is the implementation. The semantics and the implications of either cloning or serializing come into play when dealing with the actual implementation; so concrete implementation should decide how it should be cloned or serialized, or even if it can be cloned or serialized. So mandating cloning and serialization in all implementations is less flexible and more restrictive. The specific implementation should decide as to whether it can be cloned or serialized
7. What is an Iterator?
The Iterator interface provides methods to iterate over any Collection. We can get iterator instance from a Collection using _iterator()_ method. Iterator takes the place of Enumeration in the Java Collections Framework. Iterators allow the caller to remove elements from the underlying collection during the iteration. Java Collection iterator provides a generic way for traversal through the elements of a collection.
8. What is the difference between Enumeration and Iterator?
Enumeration is twice as fast as Iterator and uses very little memory. Enumeration is very basic and fits basic needs. But the Iterator is much safer as compared to Enumeration because it always denies other threads to modify the collection object which is being iterated by it. Iterator takes the place of Enumeration in the Java Collections Framework. Iterators allow the caller to remove elements from the underlying collection that is not possible with Enumeration. Iterator method names have been improved to make its functionality clear
Iterator | Enumeration |
The Iterator can traverse both legacies as well as non-legacy elements. | Enumeration can traverse only legacy elements. |
The Iterator is fail-fast. | Enumeration is not fail-fast. |
The Iterator is very slow compare to Enumeration. | Enumeration is fast compare to Iterator. |
The Iterator can perform remove operation while traversing the collection. | The Enumeration can perform only traverse operation on the collection. |
9. Difference between HashMap, TreeMap and LinkedHashMap?
Characteristic | HashMap | TreeMap | LinkedHashMap |
Time complexity to search and insert | O(1) | O(log n) | O(1) |
Iteration Order | Random | Sorted order according to the natural ordering | Sorted order according to the insertion order |
Is Null key support | Allowed | Not allowed | Allowed |
Is thread safe | No, we need to collections utility to make thread safe | No, we need to collections utility to make thread safe | No, we need to collections utility to make thread safe |
Interface | Map | Map, SortedMap, NavigableMap | Map |
Data structure support | LinkedList | DoublyLinkedList | |
Application | Normal processing, faster retrieval ConcurrentHashMap we can use as per the need | Required when we do the sorting and navigable features need as per the use case. | Required when we need to maintain the insertion order and when we need to implement the LRU cache. |
Key requirement | equals() and hashcode() method need to overwritten | Along with equals() and hashcode(), the comparator to implement. | equals() and hashcode() method need to overwritten |
Syntax | public class HashMap extends AbstractMap implements Map, Cloneable, Serializable | public class TreeMap extends AbstractMap implements NavigableMap, Cloneable, Serializable | public class LinkedHashMap extends HashMap implements Map |
10. Difference between ArrayList and LinkedList?
Characteristic | ArrayList | LinkedList |
Internal datastructure | Internally ArrayList uses a dynamic array to manipulate the record | LinkedList works on the doubly linked list data structure. |
Modifying the data | Insertion and deletion in the start and middle of the array list if slow | Insertion and deletion in the middle of the linked list is fast as comparison of LinkedList |
Implementation | ArrayList is implemented only List interface | LinkedList implements both List and Deque interface |
Searching performance | Searching is fast in ArrayList, all its need the index position to get the desired value | In LinkedList searching is slower, because it needs to traverse the entire list |
Complexity | In ArrayList, the search complexity is O(1) | In LinkedLis,t the search complexity is O(n) |
Declare and adding the data in the list | List<String>arrayList=new ArrayList<String>();//creating arraylist arrayList.add(“Java”); arrayList.add(“Spring”); arrayList.add(“Junit”); arrayList.add(“jdbc”); | List<String>linkedList=new LinkedList<String>();//creating linkedlist linkedList.add(“James”);//adding object in linkedlist linkedList.add(“Serena”); linkedList.add(“Swati”); linkedList.add(“Junaid”); |
Authored by codingknownsense.com