PS: If you like the page or have any questions, feel free to comment at end.
PS: If you like the page or have any questions, feel free to comment at end of the page.
Java collections offers some of the most comprehnesive suite of built in Data structures. Often this is most common topic amongst interviewers. Good foundation and understanding of java collections helps to program effectively.
Q1) What is difference between an ArrayList and a vector?
Synchronization - ArrayList is not thread-safe whereas Vector is thread-safe. In Vector class each method like add(), get(int i) is surrounded with a synchronized block, thus making Vector class thread-safe.
Data growth - Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.
Performance - Since vector is thread-safe, the performance is slower than ArrayList.
Q2) How can an Arraylist be synchronized without using Vector?
Ans) Arraylist can be synchronized using:
Other collections can be synchronized:
Q3) If an Employee class is present and its objects are added in an arrayList. Now I want the list to be sorted on the basis of the employeeID of Employee class. What are the steps?
Implement Comparable interface for the Employee class and override the compareTo(Object obj) method in which compare the employeeID
Now call Collections.sort() method and pass the list as an argument.
Now consider that Employee class is a jar file.
1) Since Comparable interface cannot be implemented, create Comparator and override the compare(Object obj, Object obj1) method .
2) Call Collections.sort() on the list and pass comparator as an argument.
Q4)What is difference between HashMap and HashTable?
Ans) Both collections implements Map. Both collections store value as key-value pairs.
The key differences between the two are:
Hashmap is not synchronized in nature but hashtable is(thread-safe). This means that in a multithreaded application, only one thread can gets access to a hashtable object and do an operation on it. Hashmap doesn't gurantee such behavior and is not used in multithreaded environment.
Hashmap is traveresed using an iterator, hashtable can be traversed by enumerator or iterator.
Iterator in hashmap is fail-fast, enumerator in hashtable is not fail-fast
HashMap permits null values and only one null key, while Hashtable doesn't allow key or value as null.
Since hashtable is synchronized, it is relatively slower in performance than hashmap
Q5) What are the classes implementing the List interface?
Ans) There are three implementation of List interface:
ArrayList : It is a resizable array implementation. The size of the ArrayList can be increased dynamically also operations like add,remove and get can be formed once the object is created. It also ensures that the data is retrieved in the manner it was stored. The ArrayList is not thread-safe.
Vector: It is thread-safe implementation of ArrayList. The methods are wrapped around a synchronized block.
LinkedList: the LinkedList implements Queue interface too and provide FIFO (First In First Out) operation for add operation. It is faster than ArrayList if its mainly used forinsertion and deletion of elements.
Q6) Which all classes implement Set interface ?
Ans) A Set is a collection that contains no duplicate elements. More formally, a set contains no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. HashSet,SortedSet and TreeSet are the commonly used class which implements Set interface.
SortedSet - It is an interface which extends Set. A the name suggest, the interface allows the data to be iterated in the ascending order or sorted on the basis of Comparator or Comparable interface. All elements inserted into the interface must implement Comparable or Comparator interface.
TreeSet - It is the implementation of SortedSet interface. This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains). The class is not synchronized. The class uses Red-Black tree data structure.
HashSet: This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element. This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets
Q7) What is difference between List and a Set?
List can contain duplicate values but Set doesn't allow.
List allows retrieval of data to be in same order in the way it is inserted but Set doesnt ensures the sequence in which data can be retrieved.(Except HashSet)
Q8) What is difference between Arrays and ArrayList ?
Arrays are created of fix size whereas ArrayList is dynamic in nature and can vary its length. Also the size of array cannot be incremented or decremented. But with arrayList the size is variable.
Once the array is created elements cannot be added or deleted from it. But with ArrayList the elements can be added and deleted at runtime.
List list = new ArrayList();
list.remove(0) // will remove the element from the 1st location.
ArrayList is one dimensional but array can be multidimensional.
int intArray= new int; // 3 dimensional array
Array can contain objects of a single data type or class. ArrayList if not used with generic can contain objects of different classes
Q9) When to use ArrayList or LinkedList ?
Adding new elements is pretty fast for either type of list. Inserting element to nth location in arraylist and to first location in linkedlist takes O(1).
For the ArrayList, doing random lookup using "get" is faster O(1), but for LinkedList O(n), it's slow. It's slow because there's no efficient way to index into the middle of a linked list. Linkedlist lookup always start from 1st location.
When removing elements, using ArrayList is slow. This is because all remaining elements in the underlying array of Object instances must be shifted down for each remove operation. But LinkedList is fast, because deletion can be done simply by changing a couple of links.
So an ArrayList works best for cases where you're doing random access on the list and a LinkedList works better if you're doing a lot of editing in the middle of the list.
Q11) What are advantages of iterating a collection using iterator?
Ans) For loop does not allow updating the colection(add or remove) whereas Iterator does. Also Iterator can be used where there is no clue what type of collections will be used because all collections implement Iterator interface.
Q12) Which design pattern Iterator follows?
Ans) It follows Iterator design pattern. Iterator Pattern is a type of behavioral pattern.
The Iterator pattern is one, which allows you to navigate through a collection of data using a common interface without knowing about the underlying implementation.
Iterator should be implemented as an interface. This allows the user to implement it anyway its easier for him/her to return data.
The benefits of Iterator are about their strength to provide a common interface for iterating through collections without bothering about underlying implementation.
Example of Iteration design pattern - Enumeration
The class java.util.Enumeration is an example of the Iterator pattern. It represents and abstract means of iterating over a collection of elements in some sequential order without the client having to know the representation of the collection being iterated over. It can be used to provide a uniform interface for traversing collections of all kinds.