Skip to content

Latest commit

 

History

History
538 lines (332 loc) · 36.3 KB

File metadata and controls

538 lines (332 loc) · 36.3 KB

Collections

List questions:

  1. Draw Collections Framework Class Diagram
  2. The difference between List, Set, Map, and Queue in Java?
  3. What is HashMap and Map?
  4. Difference between HashMap and HashTable? Can we make HashMap synchronized?
  5. How HashSet works internally in Java?
  6. Difference between Vector and ArrayList?
  7. What is an Iterator?
  8. List vs Set vs Map. Purposes and definitions
  9. Pros and cons of ArrayList and LinkedList
  10. TreeSet and LinkedHashSet
  11. What are the advantages of ArrayList over arrays ?
  12. Principle of storing data in a hashtable
  13. Differences between Hashtable, ConcurrentHashMap and Collections.synchronizedMap()
  14. How are hash codes computed?
  15. Is it possible that hash code is not unique?
  16. Can we put two elements with equal hash code to one hash map?
  17. Iterator and modification of a List. ConcurentModificationException.
  18. What is the significance of ListIterator? What is the difference b/w Iterator and ListIterator?
  19. How can we access elements of a collection?
  20. What’s the difference between a queue and a stack?
  21. What is the Properties class?
  22. Which implementation of the List interface provides for the fastest insertion of a new element into the middle of the list?
  23. Can you limit the initial capacity of vector in Java?
  24. What method should the key class of Hashmap override?
  25. What will happen if we put a key object in a HashMap which is already there?
  26. What is the difference between Enumeration and Iterator?
  27. Collections class and Arrays class
  28. Difference between poll() and remove() method?
  29. The difference between LinkedHashMap and PriorityQueue in Java?
  30. What is a couple of ways that you could sort a collection?
  31. How do you print Array in Java?
  32. LinkedList in Java is doubly or singly linked list?
  33. Which kind of tree is used to implement TreeMap in Java?
  34. Write code to remove elements from ArrayList while iterating?
  35. Can I write my own container class and use it in the for-each loop?
  36. Is it possible for two unequal objects to have the same hashcode?
  37. Can two equal object have the different hash code?
  38. Can we use random numbers in the hashcode() method?
  39. What is the difference between Comparator and Comparable in Java?
  40. Why you need to override hashcode, when you override equals in Java?
  41. What is the benefit of Generics in Collections Framework?
  42. What is different between Iterator and ListIterator?
  43. What are different ways to iterate over a list?
  44. What is difference between Array and ArrayList? When will you use Array over ArrayList?
  45. What is difference between ArrayList and LinkedList?
  46. Which collection classes provide random access of it's elements?
  47. Which collection classes are thread-safe?
  48. What are concurrent Collection Classes?
  49. What is BlockingQueue?
  50. How can we sort a list of Objects?
  51. While passing a Collection as argument to a function, how can we make sure the function will not be able to modify it?
  52. How can we create a synchronized collection from given collection?
  53. What are best practices related to Java Collections Framework?
  54. What is fail fast iterator?
  55. What is a fail-safe iterator?
  56. Difference between fail-fast iterator and fail-safe iterator

  1. Draw Collections Framework Class Diagram
interface Iterable
interface Collection extends Iterable
interfaces List, Queue, Set extend Collection
interface SortedSet extends Set
interface Map
interface SortedMap extends Map
classes ArrayList, Vector, Stack, LinkedList implement List
classes HashSet, LinkedHashSet implement Set
class TreeSet implements SortedSet
classes HashMap, WeakHashMap, LinkedHashMap implement Map
class TreeMap implements SortedMap
utility classes Collections and Arrays
[collection in java tutorial](http://www.journaldev.com/1260/collections-in-java-tutorial)
  1. The difference between List, Set, Map, and Queue in Java?

    | | List | Set | Map | | --- | ---- | --- | --- | | Duplicate Object | Allow duplicates. |Doesn't allow duplicates. | May contain duplicate values but keys are always unique. | | Order | is an ordered collection (maintains insertion order). | is an unordered collection (Though some of the Set implementation e.g. LinkedHashSet maintains order).| | | Null elements | allows null elements and you can have many null objects in a List, because it also allowed duplicates. | allow one null element as there is no duplicate permitted. | you can have one null key and many null values. |

    When to use List, Set and Map in Java

    Based upon our understanding of difference between Set, List and Map we can now decide when to use List, Set or Map in Java.

    1. If you need to access elements frequently by using index, than List is a way to go. Its implementation e.g. ArrayList provides faster access if you know index.

    2. If you want to store elements and want them to maintain an order on which they are inserted into collection then go for List again, as List is an ordered collection and maintain insertion order.

    3. If you want to create collection of unique elements and don't want any duplicate than choose any Set implementation e.g. HashSet, LinkedHashSet or TreeSet. All Set implementation follow there general contract e.g. uniqueness but also add addition feature e.g. TreeSet is a SortedSet and elements stored on TreeSet can be sorted by using Comparator or Comparable in Java. LinkedHashSet also maintains insertion order.

    4. If you store data in form of key and value then Map is the way to go. You can choose from Hashtable, HashMap, TreeMap based upon your subsequent need.

detail

  1. What is HashMap and Map?

Map -- is a interface. Contains methods to manipulate Key-Value based collections. The main methods of Map interface are put(K,V), get(K), Collection values(), Set keySet(), containsKey(), containsValue()

HashMap -- is one of implementations of the Map interface based on hashcodes of objects used as keys.

[examples of using hashmap](http://www.java67.com/2013/02/10-examples-of-hashmap-in-java-programming-tutorial.html)
  1. Difference between HashMap and HashTable? Can we make HashMap synchronized?
  • Both implement Map interface.
  • HashTable is synchronized and slower. (It is recommended to use HashMap wherever possible - maybe?).
  • HashMap is not synchronized and faster.
  • HashTable doesn't allow null keys and values.
  • HashMap allows one null key and any number of null values.

detail

We can make it synchronized

Map m = Collections.synchronizedMap(new HashMap());
  1. How HashSet works internally in Java?

HashSet is internally implemented using an HashMap. Since a Map needs key and value, a default value is used for all keys. Similar to HashMap, HashSet doesn't allow duplicate keys and only one null key, I mean you can only store one null object in HashSet.

detail

  1. Difference between Vector and ArrayList?

Sort answer: both implement List interface. ArrayList is not synchronized.

Long answer:

ArrayList and Vector are similar classes in many ways.

  • Both are index based and backed up by an array internally.
  • Both maintains the order of insertion and we can get the elements in the order of insertion.
  • The iterator implementations of ArrayList and Vector both are fail-fast by design.
  • ArrayList and Vector both allows null values and random access to element using index number.

These are the differences between ArrayList and Vector.

  • Vector is synchronized whereas ArrayList is not synchronized. However if you are looking for modification of list while iterating, you should use CopyOnWriteArrayList.
  • ArrayList is faster than Vector because it doesn’t have any overhead because of synchronization.
  • ArrayList is more versatile because we can get synchronized list or read-only list from it easily using Collections utility class.
  1. What is an Iterator?

It is an interface that contains three methods: next(), boolean hasNext(), void remove().

Iterator interface provides methods to iterate over any Collection. We can get iterator instance from a Collection using iterator() method.

If a class implements iterator then it can be used in foreach loop.

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 and implements Iterator Design Pattern.

  1. List vs Set vs Map. Purposes and definitions

All three are interfaces.

List -- storing values in specified order.

  • Provides methods to get the element by its position: get(i), finding element, ListIterator.
  • Known implementations: ArrayList, Vector, LinkedList. List should be used when the order in which the elements are stored matters.

Set -- storing only different objects and at most one null element.

  • Known implementations: TreeSet (iterate over the elements in order defined by Comparator, or if the elements implement comparable; provides log(n) performance for basic operations), HashSet -- stores values in buckets defined by their hashcodes. Each bucket is a singly linked list. Provides constant time performance for basic operations. LinkedHashSet

Map -- for storing key-value pairs.

  • Map cannot contain duplicate keys.
  • Provides three collection views: set of keys, collection of values, set of key-value mappings.
  • Know implementations HashMap, EnumMap, TreeMap, LinkedHashMap, WeakHashMap.
  1. Pros and cons of ArrayList and LinkedList

ArrayList -- fast random access

LinkedList -- slow random access. Implement Queue interface. Fast deletion of the element.

The obvious difference between them is that ArrrayList is backed by array data structure, supprots random access and LinkedList is backed by linked list data structure and doesn't supprot random access. Accessing an element with the index is O(1) in ArrayList but its O(n) in LinkedList.

Usage:

  • If lots of random reads is anticipated use ArrayList.
  • If lots of iterations over the whole list and lots of add/delete -- use LinkedList.

detail

  1. TreeSet and LinkedHashSet

LinkedHashSet is backed by LinkedHashMap. LinkedHashMap is backed by doubly linked list to enforce ordering on the elements contained in the Map.

If the ordering of the elements in the Set matters to you but you don't want to use a comparator you may use LinkedHashSet since it will enforce ordering in which the elements were added to the set. Otherwise use TreeSet.

  1. What are the advantages of ArrayList over arrays?
  2. ArrayList comes with a number of utility methods (e.g. constants, remove, addAll)

  3. Type safety

  4. Dynamic sizing

On the other hand arrays are a little bit faster and take less memory (packing). Arrays are also able to contain values of primitive types while ArrayList can only contain Objects.

  1. Principle of storing data in a hashtable

HashSet. add(element) -> element.hashCode() -> mod bucketsCount -> store.

HashMap. add(key, value) -> key.hashCode() -> mod bucketsCount -> store(value).

  1. Differences between Hashtable, ConcurrentHashMap and Collections.synchronizedMap()

ConcurrentHashMap allows concurrent modification of the Map from several threads without the need to block them.

Collections.synchronizedMap(map) creates a blocking Map which will degrade performance, albeit ensure consistency (if used properly).

Use the second option if you need to ensure data consistency, and each thread needs to have an up-to-date view of the map. Use the first if performance is critical, and each thread only inserts data to the map, with reads happening less frequently.

  1. How are hash codes computed?

If hashCode() method is defined then it is called to calculate the hashcode.

If its not defined the default implementation in Object class does the following:

public int hashCode() {
  return VMMemoryManager.getIdentityHashCode(this);
}
  1. Is it possible that hash code is not unique?

It's totally possible. Actually a totally valid hashCode() function could look like this

int hashCode(){ return 57; }
  1. Can we put two elements with equal hash code to one hash map?

Yes we can. The hashcode of objects doesn't matter.

Only the hashcode of keys. But even if you want to put keys with the same hashcode it will be ok since it just means that key-value pairs will be put into the same bucket.

  1. Iterator and modification of a List. ConcurentModificationException.

The iterators returned by this class's iterator method are fail-fast: if the set is modified at any time after the iterator is created, in any way except through the iterator's own remove method, 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.

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

  1. What is the significance of ListIterator? What is the difference b/w Iterator and ListIterator?
  • ListIterator allows to perform iteration both ways (first-->last and last-->first)
  • From JavaDoc: ListIterator is an iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator's current position in the list
  1. How can we access elements of a collection?
  • Depends on the collection type.
  • In general: using an iterator, getting by index, getting by key, using iterator on a view
  1. What’s the difference between a queue and a stack?

In Java Queue is an interface and has a number of implementations. Stack is a class derieved from Vector class.

The Queue interface contains methods to enqueue and dequeue elements: offer(), poll(). Also contains methods to see the first element in the queue: peek(). The queue ordering is not neccessairly FIFO. It can be based on the comparator (PriorityQueue)

The Stack contains methods to add and remove elements to/from a stack. If used correctly enforces LIFO policy. Contains methods push(), pop(), peek(). The problem with Java stack implementation is that it contains all the methods from Vector class which can lead to violation of LIFO policy.

  1. What is the Properties class?
  • Property class is designed to hold properties (i.e. pairs <String, String> -- property name (key) and property value).
  • The two main methods of Properties class is getProperty(String name) and setProperty(String name, String value).
  • Properties class extends HashTable
  1. Which implementation of the List interface provides for the fastest insertion of a new element into the middle of the list?

LinkedList. It only requires 4 assignments.

Before: ... <--> A <--> B <--> ...
After:  ... <--> A <--> C <--> B <--> ...

A changes one reference, B changes one reference, C assigns two references.

  1. Can you limit the initial capacity of vector in Java?

I'm not sure if limit is correct word to be used in this question.

One can just set the initial capacity of the Vector.

Well you could say that you are putting lower limit on the size of the Vector.

  1. What method should the key class of Hashmap override?

equals() and hashCode().

  1. What will happen if we put a key object in a HashMap which is already there?

This tricky Java question is part of another frequently asked question, How HashMap works in Java. HashMap is also a popular topic to create confusing and tricky question in Java.

Answer of this question is if you put the same key again then it will replace the old mapping because HashMap doesn't allow duplicate keys.

The Same key will result in the same hashcode and will end up at the same position in the bucket. Each bucket contains a linked list of Map.Entry object, which contains both Key and Value. Now Java will take Key object form each entry and compare with this new key using equals() method, if that return true then value object in that entry will be replaced by new value. See How HashMap works in Java for more tricky Java questions from HashMap.

  1. What is the difference between Enumeration and Iterator?

Enumeration is an interface similar to Iterator. But it doesn't have remove() method.

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.

  1. Collections class and Arrays class

The Collections class contains a number of factory methods for creating unmodifiable views or synchronized wrappers of collections, as well as utility methods such as sort, shuffle, reverse

The Arrays class contains a factory method that take an array as input and return a List based on this array (Arrays.asList()). Also contains methods to sort, search, fill and print arrays

  1. Difference between poll() and remove() method?

Both poll() and remove() take out the object from the Queue but if poll() fails then it returns null but if remove fails it throws Exception.

  1. The difference between LinkedHashMap and PriorityQueue in Java?

PriorityQueue guarantees that lowest or highest priority element always remain at the head of the queue, but LinkedHashMap maintains the order on which elements are inserted. When you iterate over a PriorityQueue, iterator doesn't guarantee any order but iterator of LinkedHashMap does guarantee the order on which elements are inserted.

  1. What is a couple of ways that you could sort a collection?

You can either use the Sorted collection like TreeSet or TreeMap or you can sort using the ordered collection like a list and using Collections.sort() method.

detail

  1. How do you print Array in Java?

You can print an array by using the Arrays.toString() and Arrays.deepToString() method. Since array doesn't implement toString() by itself, just passing an array to System.out.println() will not print its contents but Arrays.toString() will print each element.

detail

  1. LinkedList in Java is doubly or singly linked list?

It's a doubly linked list, you can check the code in JDK

  1. Which kind of tree is used to implement TreeMap in Java?

A Red Black tree is used to implement TreeMap in Java.

  1. Write code to remove elements from ArrayList while iterating?

Key here is to check whether candidate uses ArrayList's remove() or Iterator's remove().

Here is the sample code which uses right way o remove elements from ArrayList while looping over and avoids ConcurrentModificationException.

detail

  1. Can I write my own container class and use it in the for-each loop?

Yes, you can write your own container class. You need to implement the Iterable interface if you want to loop over advanced for loop in Java, though. If you implement Collection then you by default get that property.

  1. Is it possible for two unequal objects to have the same hashcode?

Yes, two unequal objects can have same hashcode that's why collision happen in a hashmap.

The equal hashcode contract only says that two equal objects must have the same hashcode it doesn't say anything about the unequal object.

  1. Can two equal object have the different hash code?

No, thats not possible according to hash code contract.

  1. Can we use random numbers in the hashcode() method?

No, because hashcode of an object should be always same. See the answer to learning more about things to remember while overriding hashCode() method in Java.

detail

  1. What is the difference between Comparator and Comparable in Java?

    Comparable and Comparator interfaces are used to sort collection or array of objects.

    Comparable interface is used to provide the natural sorting of objects and we can use it to provide sorting based on single logic.

    Comparator interface is used to provide different algorithms for sorting and we can chose the comparator we want to use to sort the given collection of objects.

Comparable can be always one, but we can have multiple comparators to define customized order for objects.

detail

  1. Why you need to override hashcode, when you override equals in Java?

Because equals have code contract mandates to override equals and hashcode together .since many container class like HashMap or HashSet depends on hashcode and equals contract.

detail

  1. What is the benefit of Generics in Collections Framework?

    Java 1.5 came with Generics and all collection interfaces and implementations use it heavily. 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. I would highly recommend to go through Java Generic Tutorial to understand generics in a better way.

  2. What is different between Iterator and ListIterator?

    We can use Iterator to traverse Set and List collections whereas ListIterator can be used with Lists only.

    Iterator can traverse in forward direction only whereas ListIterator can be used to traverse in both the directions.

    ListIterator inherits from Iterator interface and comes with extra functionalities like adding an element, replacing an element, getting index position for previous and next elements.

  3. What are different ways to iterate over a list?

    We can iterate over a list in two different ways – using iterator and using for-each loop.

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

    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);
    }
  4. What is difference between Array and ArrayList? When will you use Array over ArrayList?
    • Arrays can contain primitive or Objects whereas ArrayList can contain only Objects.

    • Arrays are fixed size whereas ArrayList size is dynamic.

    • Arrays doesn’t provide a lot of features like ArrayList, such as addAll, removeAll, iterator etc.

    Although ArrayList is the obvious choice when we work on list, there are few times when array are good to use.

    • If the size of list is fixed and mostly used to store and traverse them.

    • For list of primitive data types, although Collections use autoboxing to reduce the coding effort but still it makes them slow when working on fixed size primitive data types.

    • If you are working on fixed multi-dimensional situation, using [][] is far more easier than List<List<>>

  5. What is difference between ArrayList and LinkedList?

    ArrayList and LinkedList both implement List interface but there are some differences between them.

    • ArrayList is an index based data structure backed by Array, so it provides random access to it’s elements with performance as O(1) but LinkedList stores data as list of nodes where every node is linked to it’s previous and next node. So even though there is a method to get the element using index, internally it traverse from start to reach at the index node and then return the element, so performance is O(n) that is slower than ArrayList.

    • Insertion, addition or removal of an element is faster in LinkedList compared to ArrayList because there is no concept of resizing array or updating index when element is added in middle.

    • LinkedList consumes more memory than ArrayList because every node in LinkedList stores reference of previous and next elements.

  6. Which collection classes provide random access of it's elements?

    ArrayList, HashMap, TreeMap, Hashtable classes provide random access to it's elements.

  7. Which collection classes are thread-safe?

    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.

  8. What are concurrent Collection Classes?

    Java 1.5 Concurrent package (java.util.concurrent) contains thread-safe collection classes that allow collections to be modified while iterating.

    By design Iterator implementation in java.util packages are fail-fast and throws ConcurrentModificationException. But Iterator implementation in java.util.concurrent packages are fail-safe and we can modify the collection while iterating. Some of these classes are CopyOnWriteArrayList, ConcurrentHashMap, CopyOnWriteArraySet.

  9. What is BlockingQueue?

    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 it’s handled by implementation classes of BlockingQueue.

    Java provides several BlockingQueue implementations such as ArrayBlockingQueue, LinkedBlockingQueue, PriorityBlockingQueue, SynchronousQueue etc. Check this post for use of BlockingQueue for producer-consumer problem.

  10. How can we sort a list of Objects?

    If we need to sort an array of Objects, we can use Arrays.sort(). If we need to sort a list of objects, we can use Collections.sort(). Both these classes have overloaded sort() methods for natural sorting (using Comparable) or sorting based on criteria (using Comparator).

    Collections internally uses Arrays sorting method, so both of them have same performance except that Collections take sometime to convert list to array.

  11. While passing a Collection as argument to a function, how can we make sure the function will not be able to modify it?

    We can create a read-only collection using Collections.unmodifiableCollection(Collection c) method before passing it as argument, this will make sure that any operation to change the collection will throw UnsupportedOperationException.

  12. How can we create a synchronized collection from given collection?

    We can use Collections.synchronizedCollection(Collection c) to get a synchronized (thread-safe) collection backed by the specified collection.

  13. What are best practices related to Java Collections Framework?
    • Chosing the right type of collection based on the need, for example if size is fixed, we might want to use Array over ArrayList. If we have to iterate over the Map in order of insertion, we need to use TreeMap. If we don’t want duplicates, we should use Set.

    • Some collection classes allows to specify the initial capacity, so if we have an estimate of number of elements we will store, we can use it to avoid rehashing or resizing.

    • Write program in terms of interfaces not implementations, it allows us to change the implementation easily at later point of time.

    • Always use Generics for type-safety and avoid ClassCastException at runtime.

    • Use immutable classes provided by JDK as key in Map to avoid implementation of hashCode() and equals() for our custom class. Use Collections utility class as much as possible for algorithms or to get read-only, synchronized or empty collections rather than writing own implementation. It will enhance code-reuse with greater stability and low maintainability.

  14. What is fail fast iterator?

    An iterator is considered fail-fast if it throws a ConcurrentModificationException under either of the following two conditions:

    • In multi-threaded environment, if one thread is trying to modify a Collection while another thread is iterating over it.
    • Even with single thread, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception.

    fail-fast iterator will throw a ConcurrentModificationException if the underlying collection is structurally modified in any way except through the iterator's own remove or add (if applicable as in list-iterator) methods.

    Note that structural modification is any operation that adds or deletes one or more elements; merely setting the value of an element (in case of list) or changing the value associated with an existing key (in case of map) is not a structural modification.

  15. What is a fail-safe iterator?

    An iterator is considered fail-safe if it does not throw ConcurrentModificationException. ConcurrentModificationException is not thrown as the fail-safe iterator makes a copy of the underlying structure and iteration is done over that snapshot.

    Since iteration is done over a copy of the collection so interference is impossible and the iterator is guaranteed not to throw ConcurrentModificationException.

  16. Difference between fail-fast iterator and fail-safe iterator.
    • fail-fast iterator throws a ConcurrentModificationException if the underlying collection is structurally modified whereas fail-safe iterator doesn't throw ConcurrentModificationException.
    • fail-fast iterator doesn't create a copy of the collection whereas fail-safe iterator makes a copy of the underlying structure and iteration is done over that snapshot.
    • fail-fast iterator provides operations like remove, add and set (in case of ListIterator) whereas in case of fail-safe iterators element-changing operations on iterators themselves (remove, set and add) are not supported. These methods throw UnsupportedOperationException.

References

  1. java collections tutorial
  2. java collections interview question