Tuesday, January 28, 2014

The interviews...

Hashmap in Java:  Hashmap is an unsynchronized map that implements hashing to locate bucket locations in the backing Entry<K,V> array.  The hashcode of an object is used in the hash(int h) method to determine the location for get and put operations.  It accepts null values and keys.  Typically a put will replace an old value in the bucket location if the new key and the old key are equal according to their equals() method.  However, if two keys that aren't equal via .equals() result in the same hashcode, the object will be stored in a linkedlist-like structure (Entry.next).  This is collision.  If collision occurs, the objects can still be found.  When get is called, the hashcode is determined as normal, and then the proper value is found by comparing keys of the entries with .equals().  Remember, the Entry an object that encapsulates key, value, next, and hash.  We call .equals on the key because we don't know the value yet at this point in the get.

Substring:  Works by using the original character array, and calling a String constructor that uses an offset defined by the parameters in the String.substring() method.  As of Java 1.7, the memory leak where the reference to the original array was stored in the new string has been fixed...  The array is now copied.

Differences between Java 6 and 7:  Main differences are: Strings used in Switch statements, the <> (Diamond) operator, try with resources, and multiple catch statements.  Also, New IO 2.0.

ThreadLocal<T>:  ThreadLocal is used to generate a variable value that is local to the thread that is using it.  Each thread that reaches code blocks with ThreadLocal variables in it initialize their own copy of the variable.  The generic type argument is used in the return value of ThreadLocal's get() method.  ThreadLocal<T> has one method to be overriden in the case that it is defined as an anonymous inner class, and it is initailValue().  There seems to be a memory leak with this however, so the best way to initialize it is new ThreadLocal<T>();  then set it with value, and then get the value.

No comments:

Post a Comment