Home » Collection

Collection

Last Updated on July 9, 2023 by KnownSense

11. Difference between Set and List?
List is an ordered collection of elements and hence it maintains insertion order of elements while Set doesn’t maintain any ordering of the elements. List allows duplicate elements while Set doesn’t allow any elements. List is index-based, i.e.we can access elements in List based on Index, whereas we can’t access Set using index. Concrete implementation of List Interface are ArrayList, LinkedList, etc. Concrete implementation of Set implementations are HashSet, LinkedHashSet, TreeSet etc. we can insert any number of null values in List. But we can have only a single null value at most in Set. ListIterator can be used to traverse a List in both directions (forward and backward) however it cannot be used to traverse a Set. Using Iterator, we can traverse the elements in Set and List.

12. Difference between Stack and Queue?
Stack is a data structure which follows the principle of LIFO (Last In Fast Out) OR FILO (First In Last Out), i.e element inserted at last will be the first to be removed from the stack.
Queue is a data structure which follows the principle of FIFO (First In First Out), i.e. element inserted at first to the list will be the first to be removed from the list.
For Stack, insertion and deletion of an element are termed as PUSH and POP while for Queue, insertion, and deletion of an element are termed as  ENQUEUE and DEQUEUE.
In Java, Stack is a class present in java.util package and Queue is an interface present in java.util package

stack vs queue

13. Difference between Iterator and ListIterator?
We can traverse the elements in a List using Iterator in a forward direction. Using ListIterator, we can traverse the elements in the forward and backward direction both. Iterator can be used in these collection types: List, Set, and Queue.
ListIterator can be used in List collection only.
Iterator has the following functionalities:
– boolean hasNext()
– E next()
– void remove()
ListIterator has the following functionalities:
– void add (E e)
– boolean hasNext()
– boolean hasPrevious()
– void remove()
Iterator can only perform remove operation while traversing the elements in a collection. If we try to add elements, it will throw ConcurrentModificationException.
ListIterator can perform add, remove operation while traversing the elements in a collection. We won’t get any exception while adding element using ListIterator.

14. Difference between Comparable and Comparator?

Comparable:

A comparable object is capable of comparing itself with another object. The class itself must implement the java.lang.Comparable interface to compare its instances.
Comparable has compareTo(Object o) to sort the objects
Consider a Product class that has members like, productId, productName, ManufacturerYear. Suppose we wish to sort a list of Products based on year of productId. We can implement the Comparable interface with the Product class, and we override the method compareTo() of Comparable interface.

Comparator: 

A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator interface. Comparator has compare(Object o1, Object o2) to sort the objects.

15. Can we add a NULL element in TreeSet or HashSet?
We can add null elements in a HashSet but we cannot add null elements in a TreeSet. The reason is that TreeSet uses the compareTo() method for comparing and it throws a NullPointerException when it encounters a null element.

16. What is PriorityQueue in java?
When the objects are meant to be processed in order of priority, a PriorityQueue is used. A Queue is known to follow the First-In-First-Out method, however, there are occasions when the components of the queue must be handled in order of priority, which is where the PriorityQueue comes into play. The priority heap is the foundation of the PriorityQueue. The members of the priority queue are ordered according to natural ordering or by a Comparator provided at queue construction time.
Serializable, Iterable<E>, Collection<E>, Queue<E> interfaces are implemented by the PriorityQueue class in Java.

17. Differentiate between Arrays and ArrayList?
Java provides arrays as a fundamental functionality. ArrayList is a component of Java’s collection system. As a result, It is used to access array members, while ArrayList provides a set of methods for accessing and modifying components.
ArrayList is not a fixed-size data structure, but Array is. When creating an ArrayList object, there is no need to provide its size. Even if we set a maximum capacity, we can add more parts afterward.
Arrays can include both primitive data types and class objects, depending on the array’s definition. ArrayList, on the other hand, only accepts object entries and not primitive data types. Note that when we use arraylist.add(1);, the primitive int data type is converted to an Integer object.
Members of ArrayList are always referencing to objects at various memory locations since ArrayList can’t be constructed for primitive data types  As a result, the actual objects in an ArrayList are never kept in the same place. The references to the real items are maintained in close proximity. Whether an array is primitive or an object depends on the type of the array. Actual values for primitive kinds are continuous regions, whereas allocation for objects is equivalent to ArrayList.
Many other operations, such as indexOf() and delete(), are supported by Java ArrayList. Arrays do not support these functions.

18. Can ArrayList be made read-only?
Yes. With the help of Collections.unmodifiableList() method, we can easily make an ArrayList read-only.  This function takes a changeable ArrayList as an input and returns the ArrayList’s read-only, unmodified view.

19. What are BlockingQueue in java?
BlockingQueue is an interface that has been included along with a number of other concurrent Utility classes such as ConcurrentHashMap, Counting Semaphore, CopyOnWriteArrayList, and so on. In addition to queueing, the BlockingQueue interface enables flow control by adding blocking if either BlockingQueue is full or empty. 
A thread attempting to enqueue an element in a full queue will be blocked until another thread clears the queue, either by dequeuing one or more elements or by clearing the queue entirely. It also prevents a thread from deleting from an empty queue until another thread inserts an item. A null value is not accepted by BlockingQueue. Implementations of the Java BlockingQueue interface are thread-safe. BlockingQueue’s methods are all atomic and use internal locks or other forms of concurrency management.

20.Difference between fail-fast and fail-safe iterator?
If the collection’s structure is changed, Fail-Fast iterators immediately throw ConcurrentModificationException. While a thread is iterating over a collection, structural alteration includes adding or deleting any element. Fail-safe Iterator classes include ArrayList Iterator and HashMap Iterator. Fail-fast iterators use an internal indicator called modCount, which is updated each time a collection is modified, to determine if the collection has been structurally modified or not. When a fail-fast iterator gets the next item (through the next() method), it checks the modCount flag, and if it discovers that the modCount has been changed after the iterator was generated, it throws a ConcurrentModificationException.
If a collection is structurally updated while iterating over it, fail-safe iterators don’t throw any exceptions. Because they operate on a clone of the collection rather than the original collection, they are referred to as fail-safe iterators. Fail-safe Iterators include the CopyOnWriteArrayList and ConcurrentHashMap classes.

Fail-FastFail-Safe
These types of iterators do not allow modifying the collection while iterating over it.These types of iterators allow modifying the collection while iterating over it.
It throws ConcurrentModificationException if the collection is modified while iterating over it.No exception is thrown if the collection is modified while iterating over it.
It uses the original collection while traversing the elements.It uses a copy of the original collection while traversing over it.
No extra memory is required in this case.Extra memory is required in this case.

Authored by codingknownsense.com

Scroll to Top