Monday, 24 February 2014

Java Interview Questions and Answers

JAVA INTERVIEW QUESTIONS & ANSWERS

HashSet


Java Hash Set is a useful class implementation of Java Collection framework. HashSet implements Serializable, Cloneable, Iterable<E>, Collection<E> and Set<E> interfaces and extends AbstractSet class directly.
Java Hash Set does not contains duplicate values, allows null values and does not guarantee if the order of elements will remain same over the time.
Hash Set in Java provides a huge set of implementations, some of the basic and commonly used operations are listed below with proper example.
How to create a Java Hash Set
A Java HashSet object can be obtained as shown below, gnerics specification is optional but it is always a good practice to tell JVM about the content that is going to be stored in HashSet. Use of generics eleminates the need of explicit type casting.
  1. // creating a new hash set with String  elements  
  2. HashSet<String> hashSet = new HashSet<String>(); // using generics --String in this case  
  3.          

How to add Elements to a Java Hash Set - add() & addAll()
Java HashSet provides two methods to add elements to it, add() adds a single object at a time while addAll() can be used to add all elements from a specified collection to the HashSet.
  1. // adding elements to hash set  
  2. hashSet.add("element1"); // add elements  
  3.   
  4. // adding a collection using addAll()  
  5. HashSet<String> hashSet2 = new HashSet<String>(); //new Hash Set to add   
  6.   
  7. hashSet2.add("newHashSet1"); // adding elements to new Hash Set  
  8. hashSet2.add("newHashSet2");  
  9. System.out.println(hashSet2); // show elements in new hash set  
  10.   
  11. hashSet.addAll(hashSet2); // adding new hash set  
  12. System.out.println(hashSet); // elements after adding collection using addAll  
  13.          

How to remove Elements from Java Hash Set - remove() & removeAll()
Hash Set in java provides two methods to remove elements from HashSet, remove() remmoves one element while removeAll() removes all elements from HashSet that are present in specified collection.
  1. // removing elements from hash set  
  2. hashSet.remove("element1");  // remove elements  
  3. System.out.println(hashSet);  
  4.   
  5. hashSet.removeAll(hashSet2); //removes all elements present in specified collection   
  6.          

How to make Java Hash Set Empty - clear()
Java Hash Set provides clear() method to remove all elements from a HashSet, it makes HashSet an empty collection.
  1. // removing all elements from hash set  
  2. hashSet.clear();  
  3. System.out.println(hashSet); // return an empty hash set  

How to clone a Java HashSet
Creates a shallow copy of HashSet instance but elements does not coloned themeselves. While comparing a HashSet and its clone using .equals(), it always returns a 'true'.
  1. //cloning hash set  
  2. HashSet cloneHashSet = (HashSet) hashSet.clone(); // returns a shallow copy of hash set  
  3. System.out.println(cloneHashSet);  
  4. System.out.println(hashSet.equals(cloneHashSet)); // returns a true  
  5.          

How to compare Java HashSet using .equals()
It returns true if the specified object is a set and having same size as the HashSet and contains all elements that are present in HashSet comparing to.
  1. hashSet.equals(hashSet2); // returns true if specified object is a set   
  2. //and having same size and contains all elements  
  3.          

How to check if HashSet contains specified element/elements - contains() and containsAll()
HashSet provides two very important methods, contains() returns true if the specified element is present in the HashSet and containsAll() returns true if the elements in specified collection are present in HashSet.
  1. hashSet.contains("element"); // return true if set contains specified element  
  2.   
  3. hashSet.containsAll(hashSet2); // return true if the hash set contains all the elements  
  4. //specified in provided collection  
  5.          

How to convert Java HashSet to an Array or a String
toArray() converts all HashSet elements to an array and toString() represents a String form of HashSet.
  1. hashSet.toArray(); // returns an array with hash set elements in it  
  2. hashSet.toString(); // returns a string presentation of hash set elements  
  3.          

How to use retainAll with Hash Set in Java
retainAll() method returns only those elements from HashSet that are present in the specified collection.
  1. hashSet.retainAll(hashSet2); // retain all elements that are present in specified collection   
  2. // removes all elements that are not present in specified collection  
  3.          

How to get size of a Hash Set in Java
The size of a HashSet can be obtained using .size() method, it returns an integer value equals to the number of elements in the hash set.
  1. // check size of hash Set  
  2. hashSet.size(); // returns an integer value   
  3.          

How to apply Iterator on a Java HashSet - iterator()
An iterator can be applied on a HashSet instance using .iterator() method, iteration of HashSet does not retain the order. hasNext() checks if the hash set contains more elements and .next() returns the next element in hash set.
  1. Iterator<String> iterator = hashSet.iterator(); // returned an iterator on hash set -- no order  
  2.   
  3.         while(iterator.hasNext()){  
  4.             System.out.println(iterator.next());  
  5.         } 
HashSet


HashSet is backed by HashMap instance and it stores unique elements but order in which the elements are stored is not defined, it also allows null element.


The value that is added to the HashSet acts as a key to the backing HashMap with a dummy object as the value to that key which is a static constant so that multiple add operations does not result in multiple instances of object. For example if we add a value to the hashset like
Set<String> collections= new HashSet<String>();
collections.add("HashSet");
then internally it is stored in a map as hashmap.put("HashSet",dummy) where dummy is 
private static final Object dummy = new Object();


When iterating over a HashSet a keyset iterator is returned not the values. Since the elements stored in the HashSet are stored as keys into the HashMap. 

Set Implementation Internally in Java

Each and every element in the set is unique .  So that there is no duplicate element in set .

So in java if we want to add elements in the set then we write code like this

public class Sunil {
   
    public static void main(String[] args)
    {
        // TODO Auto-generated method stub
       
        HashSet<Object> hashset = new HashSet<Object>();
        hashset.add(3);
        hashset.add("Java");
        hashset.add("Blogspot");
        System.out.println("Set is "+hashset);
    }
}

It will print the result :       Set is [3, Java , Blogspot]


Now let add duplicate element in the above code

public class Sunil {
   
    public static void main(String[] args)
    {
        HashSet<Object> hashset = new HashSet<Object>();
        hashset.add(3);
        hashset.add("Java");
        hashset.add("Blogspot");
        hashset.add(3);                     // duplicate elements
        hashset.add("Java");              // duplicate elements
        System.out.println("Set is "+hashset);
    }
}


It will print the result :       Set is [3, Java, Blogspot]


Now , what happens internally when you pass duplicate elements in the  add() method of the Set object , It will return false and do not add to the HashSet , as the element is already present .So far so good .

But the main problem arises that how it returns false . So here is the answer

When you open the HashSet implementation of the add() method in Java Api's that is rt.jar , you will find the following code in it

public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, java.io.Serializable

{
    private transient HashMap<E,Object> map;
   
    // Dummy value to associate with an Object in the backing Map
   
    private static final Object PRESENT = new Object();
   
   
   
    public HashSet() {
        map = new HashMap<>();
    }
   
    // SOME CODE ,i.e Other methods in Hash Set
   
   
    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }
   
   
   
    // SOME CODE ,i.e Other methods in Hash Set
}


So , we are achieving uniqueness in Set,internally in java  through HashMap . Whenever you create an object of HashSet it will create an object of HashMap as you can see in the italic lines in the above code .

As we know in HashMap each key is unique . So what we do in the set is that we pass the argument in the add(Elemene E) that is E as a key in the HashMap . Now we need to associate some value to the key , so what Java apis developer did is to pass the Dummy  value that is ( new Object () ) which is referred by Object reference PRESENT .

So , actually when you are adding a line in HashSet like  hashset.add(3)   what java does internally is that it will put that element E here 3 as a key in the HashMap(created during HashSet object creation) and some dummy value that is Object's object is passed as a value to the key .

Now if you see the code of the HashMap put(Key k,Value V) method , you will find something like this

 public V put(K key, V value) {
//Some code
}

The main point to notice in above code is that put (key,value) will return

1.  null , if key is unique and added to the map
2.  Old Value of the key , if key is duplicate

So , in HashSet add() method ,  we check the return value of map.put(key,value) method with null value
i.e.

   public boolean add(E e) {
            return map.put(e, PRESENT)==null;
       }

So , if map.put(key,value) returns null ,then
map.put(e, PRESENT)==null      will return true and element is added to the HashSet .



So , if map.put(key,value) returns old value of the key ,then
map.put(e, PRESENT)==null      will return false and element is  not added to the HashSet .