Monday, July 8, 2013

110 Java Collections Interview Questions


Collections Interview Questions


1. What is Java Collections API?
Ans. Java Collections framework API is a unified architecture for representing and manipulating collections. The API contains Interfaces, Implementations & Algorithm to help java programmer in everyday programming.

To be specific, there are six collection java interfaces.


The most basic interface is Collection. Three interfaces extend Collection: Set, List, and SortedSet. The other two collection interfaces, Map and SortedMap, do not extend Collection, as they represent mappings rather than true collections.

2. What is an Iterator?
Ans. Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.

3. What is the difference between java.util.Iterator and java.util.ListIterator?
Ans. ListIterator extends Iterator. The differences between the two are given below:
  • Iterator is used to iterate over any type of collection. ListIterator iterates over List only, as the name suggests.
  • Iterator traverses forward only while ListIterator traverses both forward and backward.
  • Using ListIterator, we can get the index of the element given by a subsequent call to next() or previous(). This is not possible using Iterator (Iterator also iterates over collections where index is not maintained.)
nextIndex(): Returns the index of the element that would be returned by a subsequent call to next(). previousIndex(): Returns the index of the element that would be returned by a subsequent call to previous().

  • A ListIterator can add an element at any point using add(E e) or modify an element using set(E e).
4. What is HashMap and Map?
Ans.  Map is Interface which is part of Java collections framework. This is to store Key Value pair, and Hashmap is class that implements that using hashing technique.

5. What does synchronized means in Hashtable context?
Ans. Synchronized means only one thread can modify a hash table at one point of time. Any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.


6. What is fail-fast property?
Ans. At high level - Fail-fast is a property of a system or software with respect to its response to failures. A fail-fast system is designed to immediately report any failure or condition that is likely to lead to failure. Fail-fast systems are usually designed to stop normal operation rather than attempt to continue a possibly-flawed process. When a problem occurs, a fail-fast system fails immediately and visibly. Failing fast is a non-intuitive technique: "failing immediately and visibly" sounds like it would make your software more fragile, but it actually makes it more robust. Bugs are easier to find and fix, so fewer go into production.

In Java, Fail-fast term can be related to context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally", a concurrent modification exception will be thrown. It is possible for other threads though to invoke "set" method since it doesn't modify the collection "structurally". However, if prior to calling "set", the collection has been modified structurally, "IllegalArgumentException" will be thrown.

7. Why doesn't Collection extend Cloneable and Serializable?
Ans. Many Collection implementations (including all of the ones provided by the JDK) will have a public clone method, but it would be mistake to require it of all Collections. For example, what does it mean to clone a Collection that's backed by a terabyte SQL database? Should the method call cause the company to requisition a new disk farm? Similar arguments hold for serializable. If the client doesn't know the actual type of a Collection, it's much more flexible and less error prone to have the client decide what type of Collection is desired, create an empty Collection of this type, and use the addAll method to copy the elements of the original collection into the new one.


8. What is the Difference between Enumeration and Iterator interface?
Ans. Enumeration and Iterator are the interface available in java.util package. The functionality of Enumeration interface is duplicated by the Iterator interface. New implementations should consider using Iterator in preference to Enumeration. Iterators differ from enumerations in following ways:

  1. Enumeration contains 2 methods namely hasMoreElements() & nextElement() whereas Iterator contains three methods namely hasNext(), next(),remove().
  2. Iterator adds an optional remove operation, and has shorter method names.
  3. Enumeration interface is used by legacy classes. Vector.elements() & Hashtable.elements() method returns Enumeration. Iterator is returned by all Java Collections Framework classes. java.util.Collection.iterator() method returns an instance of Iterator.
  4. The functionality of Enumeration interface is duplicated by the Iterator interface. Iterator has a remove() method while Enumeration doesn't. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, where as using Iterator we can manipulate the objects also like adding and removing the objects. So Enumeration is used when ever we want to make Collection objects as Read-only.
9. Difference between Vector and ArrayList? What is the Vector class?
Ans. Vector & ArrayList both classes are implemented using dynamically resizable arrays, providing fast random access and fast traversal. ArrayList and Vector class both implement the List interface. Both the classes are member of Java collection framework, therefore from an API perspective; these two classes are very similar. However, there are still some major differences between the two. Below are some key differences

  • Vector is a legacy class which has been retrofitted to implement the List interface since Java 2 platform v1.2
  • Vector is synchronized whereas ArrayList is not. Even though Vector class is synchronized, still when you want programs to run in multithreading environment using ArrayList with Collections.synchronizedList() is recommended over Vector.
  • ArrayList has no default size while vector has a default size of 10.
  • The Enumerations returned by Vector's elements method are not fail-fast. Whereas ArrayList does not have any method returning Enumerations.
10. Why Java Vector class is considered obsolete or unofficially deprecated? or Why should I always use ArrayList over Vector?
Ans. You should use ArrayList over Vector because you should default to non-synchronized access. Vector synchronizes each individual method. That's almost never what you want to do. Generally you want to synchronize a whole sequence of operations. Synchronizing individual operations is both less safe (if you iterate over a Vector, for instance, you still need to take out a lock to avoid anyone else changing the collection at the same time) but also slower (why take out a lock repeatedly when once will be enough)? Of course, it also has the overhead of locking even when you don't need to. It's a very flawed approach to have synchronized access as default. You can always decorate a collection using Collections.synchronizedList - the fact that Vector combines both the "resized array" collection implementation with the "synchronize every operation" bit is another example of poor design; the decoration approach gives cleaner separation of concerns. Vector also has a few legacy methods around enumeration and element retrieval which are different than the List interface, and developers (especially those who learned Java before 1.2) can tend to use them if they are in the code. Although Enumerations are faster, they don't check if the collection was modified during iteration, which can cause issues, and given that Vector might be chosen for its syncronization - with the attendant access from multiple threads, this makes it a particularly pernicious problem. Usage of these methods also couples a lot of code to Vector, such that it won't be easy to replace it with a different List implementation. Despite all above reasons Sun may never officially deprecate Vector class.


11. What is an enumeration?

Ans. An enumeration is an interface containing methods for accessing the underlying data structure from which the enumeration is obtained. It is a construct which collection classes return when you request a collection of all the objects stored in the collection. It allows sequential access to all the elements stored in the collection.


12. Where will you use Vector and where will you use ArrayList?
Ans. The basic difference between a Vector and an ArrayList is that, vector is synchronized while ArrayList is not. Thus whenever there is a possibility of multiple threads accessing the same instance, one should use Vector. While if not multiple threads are going to access the same instance then use ArrayList. Non synchronized data structure will give better performance than the synchronized one.


13. What is the importance of hashCode() and equals() methods? How they are used in Java?

Ans.  equals()
equals() is used in most collections to determine if a collection contains a given element. For instance:

list.add("Sushil");
boolean flag = list.contains("Sushil");

The ArrayList iterates all its elements and execute "Sushil".equals(element) to determine if the element is equal to the parameter object "Sushil".

So, when are two objects equal? That depends on your application, the classes, and what you are trying to do. For instance, let's say you are loading and processing Employee objects stored in a database. Here is a simple example of such an Employee class:

public class Employee {
    protected long   employeeId;
    protected String firstName;
    protected String lastName;
}

You could decide that two Employee objects are equal to each other if just their employeeId's are equal. Or, you could decide that all fields must be equal - both employeeId, firstName and lastName.

public class Employee {
  ...
  public boolean equals(Object o){
    if(o == null)                return false;
    if(!(o instanceof) Employee) return false;

    Employee other = (Employee) o;
    if(this.employeeId != other.employeeId)      return false;
    if(! this.firstName.equals(other.firstName)) return false;
    if(! this.lastName.equals(other.lastName))   return false;
    return true;
  }
}

hashCode()

The hashCode() method of objects is used when you insert them into a HashTable, HashMap or HashSet.
When inserting an object into a hastable you use a key. The hash code of this key is calculated, and used to determine where to store the object internally. When you need to lookup an object in a hashtable you also use a key. The hash code of this key is calculated and used to determine where to search for the object.

The hash code only points to a certain "area" (or list, bucket etc) internally. Since different key objects could potentially have the same hash code, the hash code itself is no guarantee that the right key is found. The hashtable then iterates this area (all keys with the same hash code) and uses the key's equals() method to find the right key. Once the right key is found, the object stored for that key is returned.

So, as you can see, a combination of the hashCode() and equals() methods are used when storing and when looking up objects in a hashtable.

Here are two rules that are good to know about implementing the hashCode() method in your own classes, if the hashtables in the Java Collections API are to work correctly:

  1. If object1 and object2 are equal according to their equals() method, they must also have the same hash code.
  2. If object1 and object2 have the same hash code, they do NOT have to be equal too.
14. What is the difference between Sorting performance of Arrays.sort() vs Collections.sort() ? Which one is faster? Which one to use and when?
Ans. Both methods have same algorithm the only difference is type of input to them. Collections.sort() has a input as List so it does a translation of List to array and vice versa which is an additional step while sorting. So this should be used when you are trying to sort a list. Arrays.sort is for arrays so the sorting is done directly on the array. So clearly it should be used when you have an array available with you and you want to sort it.

15. Set & List interface extend Collection, so why doesn't Map interface extend Collection?
Ans. We feel that mappings are not collections and collections are not mappings. Thus, it makes little sense for Map to extend the Collection interface (or vice versa). If a Map is a Collection, what are the elements? The only reasonable answer is "Key-value pairs", but this provides a very limited (and not particularly useful) Map abstraction. You can't ask what value a given key maps to, nor can you delete the entry for a given key without knowing what value it maps to. Collection could be made to extend Map, but this raises the question: what are the keys? There's no really satisfactory answer, and forcing one leads to an unnatural interface. Maps can be viewed as Collections (of keys, values, or pairs), and this fact is reflected in the three "Collection view operations" on Maps (keySet, entrySet, and values). While it is, in principle, possible to view a List as a Map mapping indices to elements, this has the nasty property that deleting an element from the List changes the Key associated with every element before the deleted element. That's why we don't have a map view operation on Lists.


16. Which implementation of the List interface provides for the fastest insertion of a new element into the middle of the list?
Ans. ArrayList and Vector both use an array to store the elements of the list. When an element is inserted into the middle of the list the elements that follow the insertion point must be shifted to make room for the new element. The LinkedList is implemented using a doubly linked list; an insertion requires only the updating of the links at the point of insertion. Therefore, the LinkedList allows for fast insertions and deletions.


17. What is the difference between ArrayList and LinkedList?
Ans. java.util.ArrayList and java.util.LinkedList are two Collections classes used for storing lists of object references Here are some key differences:
  • ArrayList uses primitive object array for storing objects whereas LinkedList is made up of a chain of nodes. Each node stores an element and the pointer to the next node. A singly linked list only has pointers to next. A doubly linked list has a pointer to the next and the previous element. This makes walking the list backward easier.
  • ArrayList implements the RandomAccess interface, and LinkedList does not. The commonly used ArrayList implementation uses primitive Object array for internal storage. Therefore an ArrayList is much faster than a LinkedList for random access, that is, when accessing arbitrary list elements using the get method. Note that the get method is implemented for LinkedLists, but it requires a sequential scan from the front or back of the list. This scan is very slow. For a LinkedList, there's no fast way to access the Nth element of the list.
  • Adding and deleting at the start and middle of the ArrayList is slow, because all the later elements have to be copied forward or backward. (Using System.arrayCopy()) Whereas Linked lists are faster for inserts and deletes anywhere in the list, since all you do is update a few next and previous pointers of a node.
  • Each element of a linked list (especially a doubly linked list) uses a bit more memory than its equivalent in array list, due to the need for next and previous pointers.
  • ArrayList may also have a performance issue when the internal array fills up. The arrayList has to create a new array and copy all the elements there. The ArrayList has a growth algorithm of (n*3)/2+1, meaning that each time the buffer is too small it will create a new one of size (n*3)/2+1 where n is the number of elements of the current buffer. Hence if we can guess the number of elements that we are going to have, then it makes sense to create a arraylist with that capacity during object creation (using construtor new ArrayList(capacity)). Whereas LinkedLists should not have such capacity issues.
18. Where will you use ArrayList and Where will you use LinkedList? Or Which one to use when (ArrayList / LinkedList).
Ans. If you frequently add elements to the beginning of the List or iterate over the List to delete elements from its interior, you should consider using LinkedList. These operations require constant-time in a LinkedList and linear-time in an ArrayList. But you pay a big price in performance. Positional access requires linear-time in a LinkedList and constant-time in an ArrayList.

19. 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?
Ans. 1) Implement Comparable interface for the Employee class and override the compareTo(Object obj) method in which compare the employeeID
2) Now call Collections.sort() method and pass 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.

20. What are the classes implementing List interface?
Ans. There are three classes that implement List interface:
1) 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.
2) Vector: It is thread-safe implementation of ArrayList. The methods are wrapped around a synchronized block.
3) LinkedList: the LinkedList also implements Queue interface and provide FIFO(First In First Out) operation for add operation. It is faster if than ArrayList if it performs insertion and deletion of elements from the middle of a list.

Q21. What is difference between Arrays and ArrayList?
Ans. Arrays are created of fix size whereas ArrayList is of not fix size. It means that once array is declared as :

  1. int [] intArray= new int[6];
  2. intArray[7]   // will give ArraysOutOfBoundException.
Also the size of array cannot be incremented or decremented. But with arrayList the size is variable.

  1. 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.add(1);
list.add(3);
list.remove(0) // will remove the element from the 1st location.

  1. ArrayList is one dimensional but array can be multidimensional.
            int[][][] intArray= new int[3][2][1];   // 3 dimensional array    

  1. To create an array the size should be known or initalized to some value. If not initialized carefully there could me memory wastage. But arrayList is all about dynamic creation and there is no wastage of memory.
22. Consider a scenario. If an ArrayList has to be iterate to read data only, what are the possible ways and which is the fastest?
Ans. It can be done in two ways, using for loop or using iterator of ArrayList. The first option is faster than using iterator. Because value stored in arraylist is indexed access. So while accessing the value is accessed directly as per the index.

23. Now another question with respect to above question is if accessing through iterator is slow then why do we need it and when to use it?
Ans. For loop does not allow the updation in the array(add or remove operation) inside the loop whereas Iterator does. Also Iterator can be used where there is no clue what type of collections will be used because all collections have iterator.

24. Why is it preferred to declare:
List<String> list = new ArrayList<String>();
instead of ArrayList<String> = new ArrayList<String>();
Ans. It is preferred because:

  1. If later on code needs to be changed from ArrayList to Vector then only at the declaration place we can do that.
  2. The most important one – If a function is declared such that it takes list. E.g void showDetails(List list);
    When the parameter is declared as List to the function it can be called by passing any subclass of List like ArrayList,Vector,LinkedList making the function more flexible.
25. What is difference between iterator access and index access?
Ans. Index based access allow access of the element directly on the basis of index. The cursor of the data structure can directly go to the 'n' location and get the element. It doesn’t traverse through n-1 elements.
In Iterator based access, the cursor has to traverse through each element to get the desired element. So to reach the 'n'th element it need to traverse through n-1 elements.
Insertion, updation or deletion will be faster for iterator based access if the operations are performed on elements present in between the data structure.
Insertion, updation or deletion will be faster for index based access if the operations are performed on elements present at last of the data structure.
Traversal or search in index based data structure is faster.
ArrayList is index access and LinkedList is iterator access.

26. How to sort list in reverse order?
Ans. To sort the elements of the List in the reverse natural order of the strings, get a reverse Comparator from the Collections class with reverseOrder(). Then, pass the reverse Comparator to the sort() method.
List list = new ArrayList();
Comparator comp = Collections.reverseOrder();
Collections.sort(list, comp)

27. How to sort list of strings - case insensitive?
Ans. using Collections.sort(list, String.CASE_INSENSITIVE_ORDER);

28. How to make a List (ArrayList,Vector,LinkedList) read only?
Ans. A list implemenation can be made read only using  Collections.unmodifiableList(list). This method returns a new list. If a user tries to perform add operation on the new list; UnSupportedOperationException is thrown.

29. How to convert a string array to arraylist?
Ans. new ArrayList(Arrays.asList(myArray));

30. Why insertion and deletion in ArrayList is slow compared to LinkedList?
  • ArrayList internally uses and array to store the elements, when that array gets filled by inserting elements a new array of roughly 1.5 times the size of the original array is created and all the data of old array is copied to new array.
  • During deletion, all elements present in the array after the deleted elements have to be moved one step back to fill the space created by deletion. In linked list data is stored in nodes that have reference to the previous node and the next node so adding element is simple as creating the node an updating the next pointer on the last node and the previous pointer on the new node. Deletion in linked list is fast because it involves only updating the next pointer in the node before the deleted node and updating the previous pointer in the node after the deleted node.
 31. What is difference between Comparable and Comparator?

Comparable
Comparator
1) Comparable provides only one sort of sequence.
1) Comparator provides multiple sorts of sequences.
2) It provides one method named compareTo().
2) It provides one method named compare().
3) It is found in java.lang package.
3) It is found in java.util package.
4) If we implement Comparable interface, actual class is modified.
4) Actual class is not modified
Comparators and comparable in Java are two of fundamental interface of Java API which is very important to understand to implement sorting in Java. It’s often required to sort objects stored in any collection class or in Array and that time we need to use compare () and compare To () method defined in java.util.Comparator and java.lang.Comparable class. Let’s see some important points about both Comparable and Comparator in Java before moving ahead

1) Comparator in Java is defined in java.util package while Comparable interface in Java is defined in java.lang package.
2) Comparator interface in Java has method public int compare (Object o1, Object o2) which returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. While Comparable interface has method public int compareTo(Object o) which returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
3) If you see then logical difference between these two is Comparator in Java compare two objects provided to him, while Comparable interface compares "this" reference with the object specified.
4) Comparable in Java is used to implement natural ordering of object. In Java API String, Date and wrapper classes implement Comparable interface.
5) If any class implement Comparable interface in Java then collection of that object either List or Array can be sorted automatically by using Collections.sort() or Arrays.sort() method and object will be sorted based on their natural order defined by CompareTo() method.
6)Objects which implement Comparable in Java can be used as keys in a sorted map or elements in a sorted set for example TreeSet, without specifying any Comparator.

So in Summary if you want to sort based on natural order or object then use Comparable in Java and if you want to sort on some other attribute of object then Comparator in Java is the way to go.

How to Compare String in Java
For comparing String in Java we should not be worrying because String implements Comparable interface in Java and provides implementation for CompareTo method which Compare two strings based on characters inside or you can say in lexical order. You just need to call String.compareTo(AnotherString) and Java will determine whether specified String is greater than , equal to or less than current String.

String is also immutable in Java an important property to remember.

How to Compare Dates in Java
Dates are represented by java.util.Date class in Java and like String Dates also implements Comparable in Java so they will be automatically sorted based on there natural ordering if they got stored in any sorted collection like TreeSet or TreeMap. If you explicitly wants to compare two dates in Java you can call Date.compareTo(AnotherDate) method in Java and it will tell whether specified date is greater than , equal to or less than current String.

32. What is difference between HashSet and HashMap?
Ans. HashSet contains only values whereas HashMap contains entry(key and value).

33. What is Property Class?
Ans.  Properties is a subclass of Hashtable. It is used to maintain lists of values in which the key is a String and the value is also a String.
The Properties class is used by many other Java classes. For example, it is the type of object returned by System.getProperties( ) when obtaining environmental values.

34. What is MAP and SortedMap interface?
Ans. A Map is an object that maps keys to values. It is not an extension of the collection interface rather it has own interface hierarchy. Map provides a more general way for storing elements without containing duplicate keys. It allows you to store pairs of elements, termed "keys" and "values", where each key maps to one value. Thus the keys in a map must be unique.
Each element in a map has a key and value. Each key-value pair is saved in a java.util.Map.Entry object. A set of these map entries can be obtained by calling a map's entrySet( ) method.

SortedMap interface:
The Collection Framework provides a special Map interface for maintaining elements in a sorted order called SortedMap. The SortedMap interface extends the Map interface which maintains its elements in ascending order. Working with a SortedMap is just similar to a SortedSet except, the sort is done on the map keys. In addition to methods of the Map interface, it provides two methods:
The firstKey( ) method returns the first lowest value currently in the map while the lastKey( ) method returns
the last highest value currently in the map.

35. What is the difference between set and list?
Ans. A Set stores elements in an unordered way and does not contain duplicate elements, whereas a list stores elements in an ordered way but may contain duplicate elements.

36. What is an Iterator interface? Is Iterator a Class or Interface? What is its use?
Ans. The Iterator is an interface, used to traverse through the elements of a Collection. It is not advisable to modify the collection itself while traversing an Iterator.

37. How can we access elements of a collection?
Ans. We can access the elements of a collection using the following ways:
1.Every collection object has get(index) method to get the element of the object. This method will return Object.
2.Collection provide Enumeration or Iterator object so that we can get the objects of a collection one by one.

38. What are differences Collections and Collection?
Ans. Collections: It implements Polymorphic algorithms which operate on collections.

Collection: It is the root interface in the collection hierarchy.

39. Why there is not method like Iterator.add() to add elements to the collection?
Ans. The semantics are unclear, given that the contract for Iterator makes no guarantees about the order of iteration. Note, however, that ListIterator does provide an add operation, as it does guarantee the order of the iteration

40. What are different ways to iterate over a list?
Ans. We can iterate over a list in two different ways – using iterator and using for-each loop.

List<String> strList = new ArrayList<>();

//using for-each loop
for(String obj : strList){
    System.out.println(obj);
}

//using iterator
Iterator<String> it = strList.iterator();
while(it.hasNext()){
    String obj = it.next();
    System.out.println(obj);
}

Using iterator is more thread-safe because it makes sure that if underlying list elements are modified, it will throw ConcurrentModificationException.

41. Why there are no concrete implementations of Iterator interface?
Ans. Iterator interface declare methods for iterating a collection but it’s implementation is responsibility of the Collection implementation classes. Every collection class that returns an iterator for traversing has it’s own Iterator implementation nested class.
This allows collection classes to choose whether iterator is fail-fast or fail-safe. For example ArrayList iterator is fail-fast whereas CopyOnWriteArrayList iterator is fail-safe. 

42.  How HashMap works in Java?
Ans. HashMap stores key-value pair in Map.Entry static nested class implementation. HashMap works on hashing algorithm and uses hashCode() and equals() method in put and get methods.

When we call put method by passing key-value pair, HashMap uses Key hashCode() with hashing to find out the index to store the key-value pair. The Entry is stored in the LinkedList, so if there are already existing entry, it uses equals() method to check if the passed key already exists, if yes it overwrites the value else it creates a new entry and store this key-value Entry.

When we call get method by passing Key, again it uses the hashCode() to find the index in the array and then use equals() method to find the correct Entry and return it’s value. Below image will explain these detail clearly.
The other important things to know about HashMap are capacity, load factor, threshold resizing. HashMap initial default capacity is 32 and load factor is 0.75. Threshold is capacity multiplied by load factor and whenever we try to add an entry, if map size is greater than threshold, HashMap rehashes the contents of map into a new array with a larger capacity. The capacity is always power of 2, so if you know that you need to store a large number of key-value pairs, for example in caching data from database, it’s good idea to initialize the HashMap with correct capacity and load factor.

43. What are different Collection views provided by Map interface?
Ans. Map interface provides three collection views:

  1. Set keySet(): Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator’s own remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.
  2. Collection values(): Returns a Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa. If the map is modified while an iteration over the collection is in progress (except through the iterator’s own remove operation), the results of the iteration are undefined. The collection supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Collection.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.
  3. Set<Map.Entry<K, V>> entrySet(): Returns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator’s own remove operation, or through the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.
44.  Which collection classes provide random access of it’s elements?
Ans. ArrayList, HashMap, TreeMap, Hashtable classes provide random access to its elements.

45. Which collection classes are thread-safe?
Ans. Vector, Hashtable, Properties and Stack are synchronized classes, so they are thread-safe and can be used in multi-threaded environment. Java 1.5 Concurrent API included some collection classes that allows modification of collection while iteration because they work on the clone of the collection, so they are safe to use in multi-threaded environment.

46. What are concurrent Collection Classes?
Ans. Java 1.5 Concurrent package (java.util.concurrent) contains thread-safe collection classes that allow collections to be modified while iterating. By design iterator is fail-fast and throws ConcurrentModificationException. Some of these classes are CopyOnWriteArrayList, ConcurrentHashMap,CopyOnWriteArraySet.

47. What is BlockingQueue?
Ans. java.util.concurrent.BlockingQueue is a Queue that supports operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element.

BlockingQueue interface is part of java collections framework and it’s primarily used for implementing producer consumer problem. We don’t need to worry about waiting for the space to be available for producer or object to be available for consumer in BlockingQueue as its handled by implementation classes of BlockingQueue.

48. Can a null element added to a TreeSet or HashSet?
Ans. A null element can be added only if the set contains one element because when a second element is added then as per set definition a check is made to check duplicate value and comparison with null element will throw NullPointerException.
HashSet is based on hashMap and can contain null element.

49. What is ConcurrentHashMap?
Ans. A concurrentHashMap is thread-safe implementation of Map interface. In this class put and remove method are synchronized but not get method. This class is different from Hashtable in terms of locking; it means that hashtable use object level lock but this class uses bucket level lock thus having better performance.

50. What are the main implementations of the List interface?
Ans. The main implementations of the List interface are as follows:

  • ArrayList : Resizable-array implementation of the List interface. The best all-around implementation of the List interface.
  • Vector : Synchronized resizable-array implementation of the List interface with additional "legacy methods."
  • LinkedList : Doubly-linked list implementation of the List interface. May provide better performance than the ArrayList implementation if elements are frequently inserted or deleted within the list. Useful for queues and double-ended queues (deques).
53. What are the advantages of ArrayList over arrays ?
Ans. Some of the advantages ArrayList has over arrays are:
  • It can grow dynamically
  • It provides more powerful insertion and search mechanisms than arrays.
54. How to obtain Array from an ArrayList ?
Ans. Array can be obtained from an ArrayList using toArray() method on ArrayList.

        List arrayList = new ArrayList();
        arrayList.add(“a”);
        Object  a[] = arrayList.toArray();

55. Why insertion and deletion in ArrayList is slow compared to LinkedList ?
  • ArrayList internally uses and array to store the elements, when that array gets filled by inserting elements a new array of roughly 1.5 times the size of the original array is created and all the data of old array is copied to new array.
  • During deletion, all elements present in the array after the deleted elements have to be moved one step back to fill the space created by deletion. In linked list data is stored in nodes that have reference to the previous node and the next node so adding element is simple as creating the node an updating the next pointer on the last node and the previous pointer on the new node. Deletion in linked list is fast because it involves only updating the next pointer in the node before the deleted node and updating the previous pointer in the node after the deleted node.
58. Why are Iterators returned by ArrayList called Fail Fast ?
Ans. Because, if list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

59. How do you decide when to use ArrayList and When to use LinkedList?
Ans. If you need to support random access, without inserting or removing elements from any place other than the end, then ArrayList offers the optimal collection. If, however, you need to frequently add and remove elements from the middle of the list and only access the list elements sequentially, then LinkedList offers the better implementation.

60. What is the Set interface ?
  • The Set interface provides methods for accessing the elements of a finite mathematical set
  • Sets do not allow duplicate elements
  • Contains no methods other than those inherited from Collection
  • It adds the restriction that duplicate elements are prohibited
  • Two Set objects are equal if they contain the same elements
61. What are the main Implementations of the Set interface ?
Ans. The main implementations of the List interface are as follows:
  • HashSet
  • TreeSet
  • LinkedHashSet
  • EnumSet
62. What is a HashSet ?
  • A HashSet is an unsorted, unordered Set.
  • It uses the hashcode of the object being inserted (so the more efficient your hashcode() implementation the better access performance you’ll get).
  • Use this class when you want a collection with no duplicates and you don’t care about order when you iterate through it.
63. What is a TreeSet ?
Ans. TreeSet is a Set implementation that keeps the elements in sorted order. The elements are sorted according to the natural order of elements or by the comparator provided at creation time.

64. What is an EnumSet ?
Ans .An EnumSet is a specialized set for use with enum types, all of the elements in the EnumSet type that is specified, explicitly or implicitly, when the set is created.

65. What is a Map?
  • A map is an object that stores associations between keys and values (key/value pairs).
  • Given a key, you can find its value. Both keys  and  values are objects.
  • The keys must be unique, but the values may be duplicated.
  • Some maps can accept a null key and null values, others cannot.
66. What are the main Implementations of the Map interface?
Ans. The main implementations of the List interface are as follows:
  • HashMap
  • HashTable
  • TreeMap
  • EnumMap
67. What is a TreeMap ?
Ans. TreeMap actually implements the SortedMap interface which extends the Map interface. In a TreeMap the data will be sorted in ascending order of keys according to the natural order for the key's class, or by the comparator provided at creation time. TreeMap is based on the Red-Black tree data structure.

68. How do you decide when to use HashMap and when to use TreeMap?
Ans. For inserting, deleting, and locating elements in a Map, the HashMap offers the best alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is your better alternative. Depending upon the size of your collection, it may be faster to add elements to a HashMap, then convert the map to a TreeMap for sorted key traversal.

69. Difference between HashMap and Hashtable ?
HashMap
Hashtable
HashMap lets you have null values as well as one null key.
HashTable  does not allows null values as key and value.
The iterator in the HashMap is fail-safe (If you change   the map while iterating, you’ll know).
The enumerator for the Hashtable is not fail-safe.
HashMap is unsynchronized.
Hashtable is synchronized.

Note: Only one NULL is allowed as a key in HashMap. HashMap does not allow multiple keys to be NULL. Nevertheless, it can have multiple NULL values.

70. How the elements are sorted in TreeSet?
Ans. TreeMap actually implements the SortedMap interface which extends the Map interface. In a TreeMap the data will be sorted in ascending order of keys according to the natural order for the key's class, or by the comparator provided at creation time. TreeMap is based on the Red-Black tree data structure.

71. What is the different Collection Views That Maps Provide?
Ans. Maps Provide Three Collection Views.
  • Key Set - allow a map's contents to be viewed as a set of keys.
  • Values Collection - allow a map's contents to be viewed as a set of values.
  • Entry Set - allow a map's contents to be viewed as a set of key-value mappings.
72. What is a KeySet View?
Ans. KeySet is a set returned by the keySet() method of the Map Interface, It is a set that contains all the keys present in the Map.

73. What is a Values Collection View?
Ans. Values Collection View is a collection returned by the values() method of the Map Interface, It contains all the objects present as values in the map.

74. What is an EntrySet View?
Ans. Entry Set view is a set that is returned by the entrySet() method in the map and contains Objects of type Map. Entry each of which has both Key and Value.

75. How do you sort an ArrayList (or any list) of user-defined objects?
Ans. Create an implementation of the java.lang.Comparator interface that knows how to order your objects and pass it to java.util.Collections.sort(List, Comparator).

76. What is the Comparable interface?
Ans. The Comparable interface is used to sort collections and arrays of objects using the Collections.sort() and java.utils.Arrays.sort() methods respectively. The objects of the class implementing the Comparable interface can be ordered.

The Comparable interface in the generic form is written as follows:

        interface Comparable<T>

where T is the name of the type parameter.
All classes implementing the Comparable interface must implement the compareTo() method that has the return type as an integer. The signature of the compareTo() method is as follows:

      int i = object1.compareTo(object2)

  • If object1 < object2: The value of i returned will be negative.
  • If object1 > object2: The value of i returned will be positive.
  • If object1 = object2: The value of i returned will be zero.
77. Give one scenario in your project where you used Hashmap?
Ans. Prepare it properly there will be lot of cross questions.

78. How you remove duplicate value from Arraylist?
Ans. list=new ArrayList(new HashSet(list));

79. How will you find duplicate value in ArrayList?
Ans.  Set set=new HashSet(list);

     int j;
     for (Object in : set) {
     if((j=Collections.frequency(list, in))>=2){
    System.out.println("Duplicate no is and its frequency is "+ in + " " + j );  }  }

80. What is the main Difference Between for loop and Iterator ?
Ans.  A for loop gives you the benefit of having a pointer / counter variable with you, while an iterator does not know very much about its position in the list.

The for-each syntax allows the compiler to check type-consistency at compile time, but again, if you need the position in the list, you're better served with a for loop.

Iterators are fail fast - any operation that structurally modifies the underlying  collection    (such as remove() ) will immediately have an effect on the iterator. However, looping over an index can have potential invalid references or skip elements if you remove() elements.

Iterator provides a very handy way to loop through a list or collection, but it is slower than For loop.

Any collection that can provide an iterator can be traversed in exactly the same way, instead of having to know whether it's indexable, what the method or member is that defines size, etc etc etc. Iterator implementations thus provide an adapter to allow the same code to work on any collection passed to it.

Iterators are just generally safer I would say, no risk of accessing an index that isn't there. They also have a little more flexibility since you can go backwards and forwards with them whereas for loops only go one way and in many languages you cannot alter the value of the loop index within the loop (i.e. you cannot change the increment rate).

Q81. What are limitations of array object?
Ans. The main limitations of Object arrays are
* These are fixed in size i.e. once we created an array object there is no chance of increasing or decreasing size based on our requirement. Hence If we don’t know size in advance, arrays are not recommended to use 
* Arrays can hold only homogeneous elements.
* There is no underlying data structure for arrays and hence no readymade method support for arrays. Hence for every requirement programmer has to code explicitly
To overcome these problems collections are recommended to use.

Q82. What is difference between Collections and Collection?
Ans. Collection is an interface which can be used for representing a group of individual objects as single entity and it acts as root interface of collection frame work. Collections is an utility class to define several utility methods for Collection implemented class objects.

Q83. Explain about NavigableSet?
Ans. It is child interface of SortedSet and provides several utility methods for navigation purposes It doesn’t allows duplicates Insertion order is preserved It is introduced in 1.6 version

84. What is RandomAccess Interface?
Ans. If a collection class implements RandomAccess interface then we can access any of its element with the same speed. RandomAccess interface is marker interface and it doesn’t contains any methods. ArrayList and vector classes implements this interface.
      
Q85. How we can get synchronized version of ArrayList?

Ans. Collections class contains synchronizedList() method for this


Public static List synchronizedList(List l)
ArrayList l= new ArrayList();
List l2=Collections.synchronizedList(l);

Similarly we can get synchronized versions of Set and Map objects by the following methods.

Public static List synchronizedSet(Set s);
Public static List synchronizedMap(Map m);

Q86. What are legacy classes and interfaces present in Collections framework?

Ans. Enumeration ---Interface Dictonary ------Abstract class Hashtable -----Concrete class Properties -----Concrete class Vector -----Concrete class Stack -----Concrete class


Q87. What are limitations of Enumeration?

Ans. While iterating the elements we are not allowed to perform removal operation It is applicable only for legacy classes and it is not a universal cursor. It can retrieve the elements only in forward direction.


Q88. Explain about HashSet class?
Ans. The underlying data structure is Hashtable null values are accepted duplicates are not allowed. insertion order is based on hashcode of the object hence insertion order is not preserved best suitable if frequent operation is search operations HashSet class implements Serializable and Cloneable it is implementation class for Set interface heterogeneous objects are allowed.

Q89. If we are trying to insert duplicate values in Set what will happen?

Ans. If we are trying to insert duplicate objects to the HashSet , we won’t get any compile time or run time errors just the add(Object o) returns false and it doesn’t add that object.


Q90. What is LinkedHashSet?
Ans. It is the child class of HashSet. The main difference between HashSet and LinkedHashSet is: In the case of HashSet insertion order is not preserved, but in the case of LinkedHashSet insertion will be preserved.

Q91. Explain about TreeSet?

Ans. It is Collection object which can be used to represent a group of objects according to some sorting order. The underlying datastructure is Balanced tree Duplicates are not allowed All objects are stored according to some sorting order hence insertion order is not preserved Heterogeneous objects are not allowed violation leads to ClassCastException For an Empty TreeSet as first element null value can be inserted but after inserting that first value if we are trying to insert any other objects then we will get NullPointerException For an non empty TreeSet if we are trying to inser null value at run time u will get NullPointerException


Q92. Explain about LinkedHashMap?

Ans. It is child class of HashMap. It is exactly same as HashMap except the following difference. In the case of HashMap the insertion order is not preserved but in the case of LinkedHashMap insertion order is preserved.


Q93. What is IdentityHashMap?

Ans. It is exactly same as HashMap except the following difference. In the HashMap JVM uses equals() method to identify duplicate keys but in the case of IdentityHashMap JVM uses == operator for this.


Q94. What is WeakHashMap?

Ans. It is exactly same as HashMap except the following difference. In case of HashMap an Object is not eligible for garbage collection if it is associated with HashMap even though it dosen’t have any external references. ie HashMap dominates garbage collector. But in case of WeakHashMap, if an Object is not having any external references then it is always eligible for garabage collectoion even though it is associated with weakHashMap. ie garbage collector dominates WeakHashMap


Q95. What is TreeMap?

Ans. TreeMap can be used to store a group of objects as key-value pairs where all the entries are arranged according to some sorting order of keys. The underlying data structure is RED-BLACK Tree Duplicates keys are not allowed but values can be duplicated. Insertion order is not preserved because insertion is based on some sorting order If we are depending on Natural sorting order then keys should be homogeneous (violation leads to ClassCastException) but values need not homogeneous In case of customized sorting order we can insert heterogeneous keys and values For empty TreeMap as first entry with null values are allowed but after inserting that entry if we are trying to insert any other entry we will get NullPointerException For non empty TreeMap if we are trying to insert null keys we will get NullPointerException There are no restrictions for null values.


Q96. What is Hashtable?

Ans. Hashtable is a legacy Map and can be used to store objects as key value pairs. The underlying data sturucture is Hashtabe Duplicates keys are not allowed but duplicate values are allowed null insertion is not possible for both keys and values all methods are synchronized insertion order is not preserved because it is based on hashcode of keys heterogeneous Objects are allowed for both keys and values


Q97. What is PriorityQueue?
Ans. It represents a data structure to hold group of individual objects prior to processing based on some priority. it can be natural sorting order and it can be customized sorting order described by Comparator. It is the implementation class of Queue interface.

Few Features:
1. Insertion order is not preserved because here insertion is done based on some sorting order.
2. Duplicates are not allowed
3. null insertion is not possible even as first element also
4. If we are depending on natural sorting order Objects should be homogeneous violation leads to ClassCastException
5. If we are depending on customized sorting order Objects can be heterogeneous also.

Q98. What is Arrays class?

Ans. It is utility class for arrays. It defines several utility methods for arrays like sorting an array or searching an element in array present in java.util package


Q99. We are planning to do an indexed search in a list of objects. Which of the two Java collections should you use: ArrayList or LinkedList?

Ans. ArrayList


Q100. Why ArrayList is faster than Vector?
Ans. All methods present in the Vector are synchronized and hence any method can be executed by only one thread at a time. It slows down the execution. But in ArrayList, no method is synchronized and hence multiple thread are allowed execute simultaneously which speed up the execution.


Q101. What is Comparable interface?
Ans. This interface can be used for defining natural sorting order of the objects. It is present in java.lang package It contains a method public int compareTo(Object obj1)


Q102. What is Comparator interface?

Ans. This interface can be used for implementing customized sorting order. It is present in java.util package It contains two methods public int compare(Object ,Object)

public boolean equals(Object)

Q103. What is Entry interface? 

Ans. It is inner interface of Map. In the Map each key value pair is considered as Entry object.
 interface Map{
 //more code here
 interface Entry{ 
Object getKey() 
Object getValue()
 Object setValue(Object new) } }


Q104. What is difference between size and capacity of a Collection Object?
Ans. size means number of objects present whereas capacity means no of objects it can accommodate.


Q105. Explain about LinkedList class? 
Ans. LinkedList is a Collection implemented class which can be used for rpresenting a group of objects as a single entity. LinkedList is the implemetation class for List interface Underlying data Structure is DoubleLinkedList Allows duplicates Insertion order is preserved Allows heterogeneous objects null insertion is possible LinkedList class implements Serializable and Cloneable interface but not RandomAccess interface  Best choice if frequent operation is insertion or deletion an objects in middle but worst choice if frequent operation is retrieval.

Q106. Explain about Vector class?
Ans. Vector is a legacy collection class which can be used to represent a group of objects. It is legacy class. The underlying data structure is resizable or grow able array. Insertion order is preserved. Duplicates are allowed Heterogeneous objects are allowed It is a implemented class for List interface null insertion is possible Vector class implements RandomAccess ,Serializable,Cloneable interfaces Best Choice if frequent operation is retrieval and worst choice if frequent operation is insertion or deletion in the middle. All methods present in Vector class are synchronized hence Vector class object is thread safe.

Q107. Explain about ArrayList class? 
Ans. ArrayList is a Collection which can be used to represent a group of objects as a single entity. It is a implemented class for List interface The underlying data structure is resizable or growable array. Insertion order is preserved Duplicates are allowed Heterogeneous objects are allowed null insertion is possible This class implements RandomAccess , Serializable , Cloneable interfaces Best choice for retrieval purpose and worst if our frequent operation is insertion or deletion in the middle.


Q108. Explain about Queue interface? 
Ans. If we want to represent a group of individual objects prior to processing, then we should go for Queue interface. It is child interface of Collection interface. It has introduced in 1.5 version



No comments: