Tuesday, August 14, 2012

Java Collections FAQ


Java Collections overview: The topic that covers most part of the interview.I will provide questions I faced in my 8 years of experience.

1) Why should be override hashCode() and equals()?.

     Even though not a part of Collections.Most of the collections internally use these methods for their functionality.So this is a stock question asked by almost all interviewers.

equals() is used in HashMap,HashTable for keys and even in Set.If you don't override equals() you cant use them in above collections and many other.If you override equals just be sure that you override hashcode() method also.So to compare 2 objects based on their state and attributes and by not its identity(address bits) we should override equals and hashcode.

2) What is the need to overide equals and hashcode ,both all the time?

    equals and hashcode are bound by a joint contract that specifies if 2 objects are equal then their hashcodes should be identical.Not necessarily the other way round.(From Java specification).

3) What do we need to override hashcode and where is it used in java?.

     Collections such as HashMap,HashSet and HashTable use hashcode to determine how to store and retrieve the object in a collection.

4) How is hashtable implemented?.

     HashTable uses buckets to fill in the objects(keys) and each bucket will be identified by an identifier(hashcode) calculated using the key(object). The process of storing and retrieving objects is a 2 step process.

  1. Find the right bucket (using hashcode()).
  2. Search the bucket for the right element (using equals()).   
5) Can different objects have the same hashcode or can I give 15 as a constant hashcode?

     Yes,you can have a constant hashcode but then the search in collections will degenerate to a linear search(based on implementation).

6) How to implement a good hashcode()?

     Basic logic is to use all the instance variables used in the equals method of the same object.Other than that you can use any legal implementation.

7) If 2 hashcodes are not equal ,then calling equal on those objects return true or false?

    false,If 2 hashcodes are equal then the equals need not return true,but if 2 hashcodes are not equal then the 2 objects also should be not equal.

i.e if x.hashcode() != y.hashcode() then x.equals(y) == false;

8) Can I use transient variables in equals and hashcode?.

     No(but compiler will not complain if you use the same),transient variables after deserialization will be initialized to default values.So the state is not saved on serialization and the computed hashcode will be different on deserialization thus breaking the equlas hashcode contract.

9) Can I change an object state which is used as a key in a hashtable(the key is in the table)?.

    Yes you can change,but changing the variable state or values will change the equality of the objects and on search you might not find the value.So it is always advised to use immutable objects as keys i.e Strings or Wrapper classes.

10)   How to make a class immutable?

    Make a class immutable by following these guidelines :
  • ensure the class cannot be overridden - make the class final, or use static factories and keep constructors private
  • make fields private and final
  • force callers to construct an object completely in a single step, instead of using a no-argument constructor combined with subsequent calls to setXXX methods (that is, avoid the Java Beans convention)
  • do not provide any methods which can change the state of the object in any way - not just setXXX methods, but any method which can change state
  • if the class has any mutable object fields, then they must be defensively copied when passed between the class and its caller
11) What are collections in Java?.

     Collections are datastructure implementations provided by java for the programmer to use directly without reinventing the wheel.Collections can be used for the following operations.
  1. Add objects to the collection
  2. Remove objects from the collection
  3. Find if an object is in the collection.
  4. Retrieve an object from a collection.
  5. Iterate through the collection.
12) What are the key interfaces and classes in Collections Framework?.

     Core Interfaces are
  1. Collection
  2. List
  3. Queue
  4. Set
  5. SortedSet
  6. Map
  7. SortedMap
  8. NavigableSet
  9. NavigableMap 
13) What is the base interface of all collections?

    Collection and Map,

14) Does collection extends any other interface?If so what is the interface?.

   Yes, Iterable is the interface,with only a single method Iterator<T> iterator()

15) Why do we need to extend Iterator interface in Collections?From which version of Java this interface is introduced?.

    Implementing this interface allows an object to be the target of the "foreach" statement.From version 1.5



Note: you can find the hierarchy here Collection and Map Hierarchy
   
Note: Important classes in Collection Framework Collection classes 


16) Name the collection class which implements both List and Queue interfaces?.

      LinkedList [API]

17) Is SortedSet a class or interface?

      Interface [API]

18) What is meant by ordered collections?

      A collection can be an Ordered collection or Unordered collection.A collection is said to be ordered if you can iterate through the collection in a specific order(not-random).Ex:
  • A Hashtable is unordered.
  • ArrayList maintains order based on index.
  • LinkedHashSet maintains the insertion order.
  • TreeSet maintains the natural ordering of the elements.
19) What is a Sorted Collection?

      A Sorted collection means that the order in the collection is determined according to some rules ,known  as sort order.Sorting is based on the properties of the elements not based on the attributes like when the element is added,access time or position.

20) What is Natural order of a Collection and how is different from Sort order?.

     Most of the time the natural order is the sort order.For Strings the natural order is alphabetical order.Some of the classes have already implemented natural ordering.[Natural Order].

We can define the natural order of an object/element by implementing an interface Comparable[API].

21) What is Comparable and why is it used?.

    This interface imposes a total ordering on the objects of each class that implements it.This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method.The classes which implement this interface can be directly used in Collections.sort(List)/Arrays.sort(Object[]).

22) Should the natural order of an element be consistent with equals?If yes, then why?.

     Yes, The natural ordering of a class C are said to consistent with equals if obj1.compareTo(obj2) == 0 has the same boolean value as obj1.equals(obj2) for every object obj1 and obj2 of a class C.


     




   

No comments:

Post a Comment