DifferenceBetween - sivakrsna/Java-Interview GitHub Wiki

HashMap and Hashtable

  1. Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.
  2. Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.
  3. One of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable.

ArrayList vs Vector

  1. ArrayList is not synchronized. Vector is synchronized.
  2. ArrayList increments 50% of current array size if number of element exceeds from its capacity. Vector increments 100% means doubles the array size if total number of element exceeds than its capacity.
  3. ArrayList is not a legacy class, it is introduced in JDK 1.2. Vector is a legacy class.
  4. ArrayList is fast because it is non-synchronized. Vector is slow because it is synchronized i.e. in multithreading environment, it will hold the other threads in runnable or non-runnable state until current thread releases the lock of object.
  5. ArrayList uses Iterator interface to traverse the elements. Vector uses Enumeration interface to traverse the elements. But it can use Iterator also.

ArrayList vs LinkedList

  1. ArrayList internally uses dynamic array to store the elements. LinkedList internally uses doubly linked list to store the elements.
  2. Manipulation with ArrayList is slow because it internally uses array. If any element is removed from the array, all the bits are shifted in memory. Manipulation with LinkedList is faster than ArrayList because it uses doubly linked list so no bit shifting is required in memory.
  3. ArrayList class can act as a list only because it implements List only. LinkedList class can act as a list and queue both because it implements List and Deque interfaces.
  4. ArrayList is better for storing and accessing data. LinkedList is better for manipulating data.

HashMap vs. TreeMap vs. HashTable vs. LinkedHashMap

  • HashMap is implemented as a hash table, and there is no ordering on keys or values.
  • TreeMap is implemented based on red-black tree structure, and it is ordered by the key.
  • LinkedHashMap preserves the insertion order
  • Hashtable is synchronized, in contrast to HashMap.

HashSet Vs TreeSet Vs LinkedHashSet

Performance and Speed : First difference between them comes in terms of speed. HashSet is fastest, LinkedHashSet is second on performance or almost similar to HashSet but TreeSet is bit slower because of sorting operation it needs to perform on each insertion. TreeSet provides guaranteed O(log(n)) time for common operations like add, remove and contains, while HashSet and LinkedHashSet offer constant time performance e.g. O(1) for add, contains and remove given hash function uniformly distribute elements in bucket.

Ordering : HashSet does not maintain any order while LinkedHashSet maintains insertion order of elements much like List interface and TreeSet maintains sorting order or elements.

Internal Implementation : HashSet is backed by an HashMap instance, LinkedHashSet is implemented using HashSet and LinkedList while TreeSet is backed up by NavigableMap in Java and by default it uses TreeMap.

null : Both HashSet and LinkedHashSet allows null but TreeSet doesn't allow null but TreeSet doesn't allow null and throw java.lang.NullPointerException when you will insert null into TreeSet. Since TreeSet uses compareTo() method of respective elements to compare them which throws NullPointerException while comparing with null, here is an example:

TreeSet cities
Exception in thread "main" java.lang.NullPointerException
        at java.lang.String.compareTo(String.java:1167)
        at java.lang.String.compareTo(String.java:92)
        at java.util.TreeMap.put(TreeMap.java:545)
        at java.util.TreeSet.add(TreeSet.java:238)

Comparison : HashSet and LinkedHashSet uses equals() method in Java for comparison but TreeSet uses compareTo() method for maintaining ordering. That's why compareTo() should be consistent to equals in Java. failing to do so break general contact of Set interface i.e. it can permit duplicates.

Similarities

  1. Duplicates : All three implements Set interface means they are not allowed to store duplicates.
  2. Thread safety : HashSet, TreeSet and LinkedHashSet are not thread-safe, if you use them in multi-threading environment where at least one Thread modifies Set you need to externally synchronize them.
  3. Fail-Fast Iterator : Iterator returned by TreeSet, LinkedHashSet and HashSet are fail-fast Iterator. i.e. If Iterator is modified after its creation by any way other than Iterators remove() method, it will throw ConcurrentModificationException with best of effort. read more about fail-fast vs fail-safe Iterator here

final, finally and finalize

Final

  • Final is used to apply restrictions on class, method and variable.
  • Final class can't be inherited, final method can't be overridden and final variable value can't be changed.
  • Final variables are initialized at the time of creation except in case of blank final variable which is initialized in Constructor.
  • Final is a keyword.

Finally

  • Finally is used for exception handling along with try and catch.
  • It will be executed whether exception is handled or not.
  • This block is used to close the resources like database connection, I/O resources.
  • Finally is a block.

Finalize

  • Finalize is called by Garbage collection thread just before collecting eligible objects to perform clean up processing. * This is the last chance for object to perform any clean-up but since itโ€™s not guaranteed that whether finalize () will be called, its bad practice to keep resource till finalize call.
  • Finalize is a method.

String vs StringBuffer vs StringBuilder

  • String is immutable whereas StringBuffer and StringBuider are mutable classes.
  • StringBuffer is thread safe and synchronized whereas StringBuilder is not, thats why StringBuilder is more faster than StringBuffer.
  • String concat + operator internally uses StringBuffer or StringBuilder class.
  • For String manipulations in non-multi threaded environment, we should use StringBuilder else use StringBuffer class.

Mutability Difference String is immutable, if you try to alter their values, another object gets created, whereas StringBuffer and StringBuilder are mutable so they can change their values.

Thread-Safety Difference The difference between StringBuffer and StringBuilder is that StringBuffer is thread-safe. So when the application needs to be run only in a single thread then it is better to use StringBuilder. StringBuilder is more efficient than StringBuffer.

Situations

  • If your string is not going to change use a String class because a String object is immutable.
  • If your string can change (example: lots of logic and operations in the construction of the string) and will only be accessed from a single thread, using a StringBuilder is good enough.
  • If your string can change, and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous so you have thread-safety.