Tuesday, April 28, 2015

HashMap vs HashTable

Differences:
  1. HashMap allows null values as key and value whereas HashTable doesn't.
    maps.put(null, 7);
    maps.put(null, 15);
    The key is null and the value of 15 overwrite 7.
  2. HashMap is non synchronized whereas Hashtable is synchronized.
  3. HashTable is the only class other than vector which have method return enumerator to iterate The values.
  4. The iterator in HashMap is fail-fast iterator while the enumerator for Hashtable is not.
Similarities:
Both HashMap and HashTable does not guarantee that the order of the map will remain constant over time. 

When to use HashMap and Hashtable?

1. Single Threaded Application
HashMap should be preferred over Hashtable for the non-threaded applications.
In simple words , use HashMap in unsynchronized or single threaded applications .
2. Multi Threaded Application
We should avoid using HashTable, as the class is now obsolete in latest Jdk 1.8.
Oracle has provided a better replacement of HashTable named ConcurrentHashMap.
For multithreaded application prefer ConcurrentHashMap instead of Hashtable. 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.

HashMapHashTable
SynchronizedNoYes
Thread-SafeNoYes
Null Keys and Null valuesOne null key ,Any null valuesNot permit null keys and values
Iterator typeFail fast iteratorFail safe iterator
PerformanceFastSlow in comparision
Superclass and LegacyAbstractMap , NoDictionary , Yes

ArrayList vs Vector

Similarities
  1. Both allows null and duplicates and index based and backed up by an array internally.
  2. Both are derived from AbstractList and implements List interface.
  3. Both can be iterated with Iterator or ListIterator.
       Get the Enumeration object:
     - Enumeration e = Collections.enumeration(arrayList);
    - Vector can return enumeration of items it hold by calling elements () method.
  4. Both are fail-fast.
    The iterators returned by this class's iterator and listIterator methods are fail-fast: if the 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.

Differences
  1. Vector is synchronized but ArrayList is not.
  2. Whenever Vector crossed the threshold specified it increases itself by value specified in capacityIncrement field while you can increase size of ArrayList by calling ensureCapacity () method.
  3. Vector standard initial size is 10,standard  capacityIncrement is zero
    The size of the new data array will be the old size plus capacityIncrement, unless the value of capacityIncrement is less than or equal to zero, in which case the new capacity will be twice the old capacity; but if this new size is still smaller than minCapacity, then the new capacity will be minCapacity.
  4. ArrayList starts with a default initial capacity of 10,
  5. Java 1.7  ==>  int newCapacity = oldCapacity + (oldCapacity >> 1)
    Java 6 ====>    int newCapacity = (oldCapacity * 3)/2 + 1;
  6. Vector provides a method to get the current capacity but ArrayList doesn't ).
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.

If a thread-safe implementation is not needed, it is recommended to use ArrayList in place of Vector.

https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html
http://docs.oracle.com/javase/7/docs/api/java/util/Vector.html

Set Collection


The "java.util.Set" interface is a subtype of the "java.util.Collection" interface that:
  1. Can not contain duplicates.
  2. Allow one null element.
  • Set Implementations:
  1. java.util.EnumSet
  2. java.util.HashSet
  3. java.util.LinkedHashSet
  4. java.util.TreeSet
  5. java.util.SortedSet

HashSet is unordered collection (Doesn't maintains insertion order) , It changes the order of the  inserted elements.

LinkedHashSet guarantees that the order of the elements during iteration is the same as the order they were inserted.

TreeSet guarantees that the order of the elements when iterated is the sorting order of the elements.

  • Operations:
  1. To add elements to a Set you call its add() method.
  2. You remove elements by calling the remove(Object o) method.
Remove Duplicates from a Collection:
Suppose you have a Collection, c, and you want to create another Collection containing the same elements but with all duplicates eliminated:

Collection<Type> noDups = new HashSet<Type>(c); 

In jdk 8 you can remove duplicate using Lambdas:
c.stream().collect(Collectors.toSet()); // no duplicates

  • Iterate Elements:
//access via Iterator
Iterator iterator = setA.iterator();
while(iterator.hasNext(){
  String element = (String) iterator.next();
}


//access via new for-loop
for(Object object : setA) {
    String element = (String) object;
}
https://docs.oracle.com/javase/tutorial/collections/interfaces/set.html
http://fastlearned.blogspot.com/2012/08/java-collection.html

Map


Collection


Wednesday, April 22, 2015

Stack and Heap memory in java basic knowledge Video

String, Stringbuffer and StringBuilder in java basic knowledge Video

We should always use StringBuilder append() method rather than String "+" operator to avoid cost. 

Note that what "+" operator does is:
  1. create a new string;
  2. make a copy of the left string;
  3. append the right char/string to the end.

So, a series of "+" operation is O(n^2)-time, not O(n).
StringBuilder is smarter and you can think it as a dynamically resizing array of char.
No copies for append() and it can output a String by calling toString() method.

Note: StringBuilder has no synchronization, i.e. it is not thread-safe.
If synchronization is required, it is recommend to use StringBuffer.

http://sophie-notes.blogspot.com/2013/02/java-stringbuilder-vs-string.html

java - fill distinct objects in ArrayList

If you have a list that contains some objects that it is considered as duplication when two or three fields of these objects are equal. How ...