Thursday 6 April 2017

Java Collection Basic Questions Part 4

1) How HashMap works in Java ? HashMap works On principle of Hashing.but it is not as simple as it sounds. Hashing is the mechanism of as... thumbnail 1 summary
1) How HashMap works in Java ?

HashMap works On principle of Hashing.but it is not as simple as it sounds. Hashing is the mechanism of assigning unique code to a variable or attribute using an algorithm to enable easy retrieval. A true hashing mechanism should always return the same hashCode() when it is applied to the same object.Read More....

2) Can we use any class as Map key?

Yes we can use class as key of HashMap. HashMap store data based on hashing algorithm so before using class as key below point should be consider:

  • Class should be immutable and if don’t keep it then hash code value can be change and when you try to pull value from hash map then possibility is you won’t get same value which you will see in below java class example
  • Class must override hashcode() and equals() method
import java.util.HashMap;
import java.util.Map;

public class ClassAsKey {

    public static void main(String[] args) {
    
    Map map = new HashMap();
    Person person = new Person();
    //Print hash code of person class
    System.out.println("Hash code: "+person.hashCode());
    map.put(person, "Java Honk");
    //Print hash code of person class again
    System.out.println("Hash code: "+person.hashCode());
    //This will return same value
    System.out.println("Value: "+map.get(person)+"\n");
    
    //Now check mutability, Because person class is
    //mutable let's change person name 
    person.setName("Java Honk");
    //Print hash code of person class again
    System.out.println("Hash code: "+person.hashCode());
    //It will return you null because hash code has
    //been changed
    System.out.println("Value: "+map.get(person));

    }

}

class Person{
    
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((name == null) ? 0 
        : name.hashCode());
    return result;
    }

    @Override
    public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Person other = (Person) obj;
    if (name == null) {
        if (other.name != null)
        return false;
    } else if (!name.equals(other.name))
        return false;
    return true;
    }
}

Output :

Hash code: 31
Hash code: 31
Value: Interview Guess

Hash code: 1319958103
Value: null


3) Why Map interface does not extend the Collection interface in Java Collections Framework ?

A good answer to this is “because they are incompatible“. Collection has a method add(Object o). Map can not have such method because it need key-value pair. There are other reasons also such as Map supports keySet, valueSet etc. Collection classes does not have such views.

4) What is EnumSet?

java.util.EnumSet is Set implementation to use with enum types. All of the elements in an enum set must come from a single enum type that is specified, explicitly or implicitly, when the set is created. EnumSet is not synchronized and null elements are not allowed. It also provides some useful methods like copyOf(Collection c), of(E first, E… rest) and complementOf(EnumSet s).

5) What is BlockingQueue?

java.util.concurrent.BlockingQueue is a Queue that supports operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element.

BlockingQueue interface is part of java collections framework and it’s primarily used for implementing producer consumer problem. We don’t need to worry about waiting for the space to be available for producer or object to be available for consumer in BlockingQueue as it’s handled by implementation classes of BlockingQueue.

Java provides several BlockingQueue implementations such as ArrayBlockingQueue, LinkedBlockingQueue, PriorityBlockingQueue, SynchronousQueue etc.

6) How can we sort a list of Objects?

If we need to sort an array of Objects, we can use Arrays.sort(). If we need to sort a list of objects, we can use Collections.sort(). Both these classes have overloaded sort() methods for natural sorting (using Comparable) or sorting based on criteria (using Comparator).
Collections internally uses Arrays sorting method, so both of them have same performance except that Collections take sometime to convert list to array.

7) What is the Dictionary class?

The Java Dictionary class is an abstract class that allows all its derived classes to store data in the form of key-value pairs. Both keys and values can be objects of any type, but keys should be unique. Also, both keys and values cannot be null. For instance, if a key or value is referring to null and then inserted into a dictionary, a NullPointerException error occurs. Therefore, it’s mandatory to provide a non-null value for storing both keys and values.

8) What is  WeakHashMap ?

Elements in a weak hashmap can be reclaimed by the garbage collector if there are no other strong references to the key object, this makes them useful for caches/lookup storage.
Weak reference are not restricted to these hash tables, you can use WeakReference for single objects. They are useful to save resource, you can keep a reference to something but allow it to be collected when nothing else references it.

9) What is IdentityHashMap ?

IdentityHashMap extends AbstractMap and implements the Map interface. It uses reference equality (==) instead of object equality (equals()) when comparing keys and values.

10) Why can’t we write code as List<Number> numbers = new ArrayList<Integer>();?

Generics doesn’t support sub-typing because it will cause issues in achieving type safety. That’s why List<T> is not considered as a subtype of List<S> where S is the super-type of T. To understanding why it’s not allowed, let’s see what could have happened if it has been supported.
List listLong = new ArrayList();
listLong.add(Long.valueOf(10));
List listNumbers = listLong; // compiler error
listNumbers.add(Double.valueOf(1.23));

As you can see from above code that IF generics would have been supporting sub-typing, we could have easily add a Double to the list of Long that would have caused ClassCastException at runtime while traversing the list of Long.

11) What is Java Priority Queue?

PriorityQueue is an unbounded queue based on a priority heap and the elements are ordered in their natural order or we can provide Comparator for ordering at the time of creation. PriorityQueue doesn’t allow null values and we can’t add any object that doesn’t provide natural ordering or we don’t have any comparator for them for ordering. Java PriorityQueue is not thread-safe and provided O(log(n)) time for enqueing and dequeing operations.

12) Why can’t we create generic array? or write code as List<Integer>[] array = new ArrayList<Integer>[10];

It's because Java's arrays (unlike generics) contain, at runtime, information about its component type. So you must know the component type when you create the array. Since you don't know what T is at runtime, you can't create the array.

13) What are common algorithms implemented in Collections Framework?

Java Collections Framework provides algorithm implementations that are commonly used such as sorting and searching. Collections class contain these method implementations. Most of these algorithms work on List but some of them are applicable for all kinds of collections.
Some of them are sorting, searching, shuffling, min-max values.

14) While passing a Collection as argument to a function, how can we make sure the function will not be able to modify it?

We can create a read-only collection using Collections.unmodifiableCollection(Collection c) method before passing it as argument, this will make sure that any operation to change the collection will throw UnsupportedOperationException.

15) How remove(key) method works in HashMap ?

HashMap remove method calls removeEntryForKey method internally, which calculate the final hashValue of the key object, and then use that hashValue in the indexFor(int,int) method to find the first entry object in the appropriate bucket.

Since bucket is a LinkedList we start traversing from the first entry object which we retrieved indexFor method in the bucket. For each entry object in the bucket we compare whether hashValue and the key is equal to the calculated hashValue in the first step and the key passed as a parameter in the remove(key) method.

If desired Entry object is found , then we remove that single entry object from the LinkedList. Removing a single Entry object from the LinkedList is implemented just like removing a single object from the LinkedList.

Entry object returned by the removeEntryForKey method is then stored in the local variable e of type Entry in the remove(key) method. Return the removed entry if it is not null else return null.

16) How will you make Collections readOnly ?

We can create a read-only collection using Collections.unmodifiableCollection(Collection c) method. This will make sure that any operation to change the collection will throw UnsupportedOperationException.

No comments

Post a Comment