Showing posts with label java-collection. Show all posts
Showing posts with label java-collection. Show all posts

Wednesday, 30 January 2019

Java HashMap Interview Questions

Java HashMap Interview Questions

Here is my list of HashMap questions from Java Interviews. This list includes questions based on the internal implementation of HashMap, the Map API, how you use HashMap and common best practices while using HashMap in a Java application.


How does put() method of HashMap works in Java? (answer)
The put() method of HashMap works in the principle of hashing. It is responsible for storing an object into backend array. The hashcode() method is used in conjunction with a hash function to find the correct location for the object into the bucket. If a collision occurs then the entry object which contains both key and value is added to a linked list and that linked list is stored into the bucket location.


What is the requirement for an object to be used as key or value in HashMap? (answer)
The key or value object must implement equals() and hashcode() method. The hash code is used when you insert the key object into the map while equals are used when you try to retrieve a value from the map.


What will happen if you try to store a key which is already present in HashMap? (answer)
If you store an existing key in the HashMap then it will override the old value with the new value and put() will return the old value. There will not be any exception or error.


Can you store a null key in Java HashMap? (answer)
Yes, HashMap allows one null key which is stored at the first location of bucket array e.g. bucket[0] = value. The HashMap doesn't call hashCode() on null key because it will throw NullPointerException, hence when a user call get() method with null then the value of the first index is returned.


Can you store a null value inside HashMap in Java? (answer)
Yes, HashMap also allows null value, you can store as many null values as you want as shown in the hashmap example post in this blog.


How does HashMap handle collisions in Java? (answer)
The java.util.HashMap uses chaining to handle collisions, which means new entries, an object which contains both key and values, are stored in a linked list along with existing value and then that linked list is stored in the bucket location. In the worst case, where all key has the same hashcode, your hash table will be turned into a linked list and searching a value will take O(n) time as opposed to O(1) time.


Which data structure HashMap represents? (answer)
The HashMap is an implementation of hash table data structure which is idle for mapping one value to other e.g. id to name as you can search for value in O(1) time if you have the key.


Which data structure is used to implement HashMap in Java? (answer)
Even though HashMap represents a hash table, it is internally implemented by using an array and linked list data structure in JDK. The array is used as bucket while a linked list is used to store all mappings which land in the same bucket. From Java 8 onwards, the linked list is dynamically replaced by binary search tree, once a number of elements in the linked list cross a certain threshold to improve performance.


Can you store a duplicate key in HashMap? (answer)
No, you cannot insert duplicate keys in HashMap, it doesn't allow duplicate keys. If you try to insert an existing key with new or same value then it will override the old value but size of HashMap will not change i.e. it will remain same. This is one of the reason when you get all keys from the HashMap by calling keySet() it returns a Set, not a Collection because Set doesn't allow duplicates.


Can you store the duplicate value in Java HashMap? (answer)
Yes, you can put duplicate values in HashMap of Java. It allows duplicate values, that's why when you retrieve all values from the Hashmap by calling values() method it returns a Collection and not Set. Worth noting is that it doesn't return List because HashMap doesn't provide any ordering guarantee for key or value.

If you want to explore, you can also see Java Fundamentals: Collections course from Pluralsight to learn more about fundamental properties of different collections in Java e.g. List, Set, and Map.

Is HashMap thread-safe in Java? (answer)
No, HashMap is not thread-safe in Java. You should not share an HashMap with multiple threads if one or more thread is modifying the HashMap e.g. inserting or removing a map. Though, you can easily share a read-only HashMap.


What will happen if you use HashMap in a multithreaded Java application? (answer)
If you use HashMap in a multithreaded environment in such a way that multiple threads structurally modify the map e.g. add, remove or modify mapping then the internal data structure of HashMap may get corrupt i.e. some links may go missing, some may point to incorrect entries and the map itself may become completely useless. Hence, it is advised not to use HashMap in the concurrent application, instead, you should use a thread-safe map e.g. ConcurrentHashMap or Hashtable.


What are different ways to iterate over HashMap in Java? (answer)
Here are some of the ways to iterate over HashMap in Java:
by using keySet and iterator
by using entrySet and iterator
by using entrySet and enhanced for loop
by using keySet and get() method

You can see this article for example of each of these way to traverse an HashMap in Java.


How do you remove a mapping while iterating over HashMap in Java? (answer)
Even though HashMap provides remove() method to remove a key and a key/value pair, you cannot use them to remove a mapping while traversing an HashMap, instead, you need to use the Iterator's remove method to remove a mapping as shown in the following example:

Iterator itr = map.entrySet().iterator();

while(itr.hasNext()){
  Map.Entry current = itr.next();

  if(current.getKey().equals("matching"){
     itr.remove(); // this will remove the current entry.
  }
}

You can see that we have used Iterator.remove() method to remove the current entry while traversing the map.


In which order mappings are stored in HashMap? (answer)
Random order because HashMap doesn't provide any ordering guarantee for keys, values, or entries. When you iterate over an HashMap, you may get the different order every time you iterate over it.



Can you sort HashMap in Java? (answer)
No, you cannot sort a HashMap because unlike List it is not an ordered collection. Albeit, you can sort contents of HashMap by keys, values or by entries by sorting and then storing the result into an ordered map e.g. LinkedHashMap or a sorted map e.g. TreeMap.


What is load factor in HashMap? (answer)
A load factor is a number which controls the resizing of HashMap when a number of elements in the HashMap cross the load factor e.g. if the load factor is 0.75 and when becoming more than 75% full then resizing trigger which involves array copy.


How does resizing happens in HashMap? (answer)
The resizing happens when map becomes full or when the size of map crosses the load factor. For example, if the load factor is 0.75 and when become more than 75% full then resizing trigger which involves array copy. First, the size of the bucket is doubled and then old entries are copied into a new bucket.


How many entries you can store in HashMap? What is the maximum limit? (answer)
There is no maximum limit for HashMap, you can store as many entries as you want because when you run out of the bucket, entries will be added to a linked list which can support an infinite number of entries, of course until you exhaust all the memory you have.

Btw, the size() method of HashMap return an int, which has a limit, once a number of entries cross the limit, size() will overflow and if your program relies on that then it will break. This issue has been addressed in JDK 8 by introducing a new method called mappingCount() which returns a long value. So, you should use mappingCount() for large maps. See Java SE 8 for Really Impatient to learn more about new methods introduced in existing interfaces in JDK 8.


What is the difference between capacity and size of HashMap in Java? (answer)
The capacity denotes how many entries HashMap can store and size denotes how many mappings or key/value pair is currently present.


What will happen if two different keys of HashMap return same hashcode()? (answer)
If two keys of HashMap return same hash code then they will end up in the same bucket, hence collision will occur. They will be stored in a linked list together.


That's all about some of the important Java HashMap interview questions. I have tried to answer them as well, but if you disagree with any answer then feel free to comment. Since HashMap is a very important class in Java and equally important from Java interview point of view, it pays to understand this class and its implementation in deep.

Read more: http://www.java67.com/2017/08/top-10-java-hashmap-interview-questions.html#ixzz5e7ocz4Dt

Monday, 28 January 2019

Using Custom Classes as Keys in HashMaps

Using Custom Classes as Keys in HashMaps


Today, we are going to discuss what we need to keep in mind when we want to use our custom class as a key in HashMap.
Here, we are considering an Employee class as a key having Id, Name, DateOfBirth, Salary as the properties.

Problem Statement 1

Let's consider the implementation below of the Employee class:
public class Employee {       
    private long id;   
    private String name;   
    private Date dateOfBirth;    
    private BigDecimal salary;   
    //Getter and Setters
    // toString
}

Let's consider using the above class as a HashMap key. For the value element for the HashMap, we are choosing a string for this example:
public static void main(String[] args) {    
    HashMap<Employee,String> employeeMap = new HashMap<Employee,String>();  
    Employee employee1 = new Employee();    
    employee1.setId(1);    
    employee1.setName("Sachin");    
    employee1.setDateOfBirth(new Date(1987,2,1));    
    employee1.setSalary(new BigDecimal(100000));    
    employeeMap.put(employee1,"India");    
    // Some Business logic    
    // In the second Operation I am updating the same employee with the newly initailized Employee Object
    Employee employee2 = new Employee();    
    employee2.setId(1);    
    employee2.setName("Sachin");    
    employee2.setDateOfBirth(new Date(1987,2,1));    
    employee2.setSalary(new BigDecimal(100000));  
    // Here we wanted to update the same Employee to Japan
    employeeMap.put(employee2,"Japan");    
    System.out.println(employeeMap); 
    // Output of this will be 2 as below
    /* 
        {Employee{id=1, name='Sachin', dateOfBirth=Tue Mar 01 00:00:00 IST 3887, salary=100000}=Japan, 
        Employee{id=1, name='Sachin', dateOfBirth=Tue Mar 01 00:00:00 IST 3887, salary=100000}=India}
    */
}

Solution for Problem Statement 1

The problem was that the hashcode and the Equals method qwew generated from the Object class. employee1 and employee2's generated hashcode will be different, and two Employee objects will be present in the HashMap.
By making the Employee class implement the Object class's equals and hashcode methods, both the employee1 and employee2 hashcode and equals methods will return the same thing.
The HashMap will use the hashcode and equals method to identify the bucket where the object is present and equals to check that the properties values are same. It's going to retrieve the correct value.
Equals and hashcode implementation in the Employee class:
public class Employee {    
    private long id;    
    private String name;    
    private Date dateOfBirth;    
    private BigDecimal salary;    
    //Getter and Setters    
    // to String    
    @Override    
    public boolean equals(Object o) {        
        if (this == o) return true;        
        if (o == null || getClass() != o.getClass()) return false;        
        Employee employee = (Employee) o;        
        if (id != employee.id) return false;        
        if (name != null ? !name.equals(employee.name) : employee.name != null) return false;        
        if (dateOfBirth != null ? !dateOfBirth.equals(employee.dateOfBirth) : employee.dateOfBirth != null) return false;        
        return salary != null ? salary.equals(employee.salary) : employee.salary == null;    
    }    
    @Override    
    public int hashCode() {        
        int result = (int) (id ^ (id >>> 32));        
        result = 31 * result + (name != null ? name.hashCode() : 0);        
        result = 31 * result + (dateOfBirth != null ? dateOfBirth.hashCode() : 0);
        result = 31 * result + (salary != null ? salary.hashCode() : 0);
        return result;    
    }    
}

Problem Statement 2

Employee is a mutable object. That will create problems with a HashMap. Let's look at the code below:
public static void main(String[] args) {    
    HashMap<Employee,String> employeeMap = new HashMap<Employee,String>();  
    Employee employee1 = new Employee();   
    employee1.setId(1);   
    employee1.setName("Sachin");   
    employee1.setDateOfBirth(new Date(1987,2,1));   
    employee1.setSalary(new BigDecimal(100000));
    // Step 1
    employeeMap.put(employee1,"India");   
    for (Map.Entry<Employee, String> employeeStringEntry : employeeMap.entrySet()) {
        System.out.println(employeeStringEntry.getKey().hashCode());   
    }
    // Step 2
    // Mutating the Employee Object
    employee1.setName("Rahul");    
    for (Map.Entry<Employee, String> employeeStringEntry : employeeMap.entrySet()) {
        System.out.println(employeeStringEntry.getKey().hashCode());    
    }
    // The HashMap key is mutated and in the wrong bucket for that hashcode. 
    // Step 3
    System.out.println(employeeMap.get(employee1));    
    // Returns null    
    Employee employee2 = new Employee();   
    employee2.setId(1);   
    employee2.setName("Sachin");   
    employee2.setDateOfBirth(new Date(1987,2,1));   
    employee2.setSalary(new BigDecimal(100000));
    System.out.println(employeeMap.get(employee2)); 
    // Returns null
}

Once the Employee Object is mutated, the hashcode of that object is going to change. Now, if we try to retrieve it in step 3 (with the different hashcode), it will go to a different bucket and not be able to get the value. Now, the object placed in the HashMap is lost forever.

Solution for Problem Statement 2

Make the Key object immutable so that mutation of the key will not affect the key element of the HashMap, so the HashMap will be consistent. Below is the implementation of an immutable Employee class via with Builder pattern.
public final class Employee {
    private final long id;
    private final String name;
    private final Date dateOfBirth;
    private final BigDecimal salary;
    public Employee(EmployeeBuilder employeeBuilder) {
        this.id = employeeBuilder.id;
        this.name = employeeBuilder.name;
        this.dateOfBirth = employeeBuilder.dateOfBirth;
        this.salary = employeeBuilder.salary;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Employee employee = (Employee) o;
        if (id != employee.id) return false;
        if (name != null ? !name.equals(employee.name) : employee.name != null) return false;
        if (dateOfBirth != null ? !dateOfBirth.equals(employee.dateOfBirth) : employee.dateOfBirth != null)
            return false;
        return salary != null ? salary.equals(employee.salary) : employee.salary == null;
    }
    @Override
    public int hashCode() {
        int result = (int) (id ^ (id >>> 32));
        result = 31 * result + (name != null ? name.hashCode() : 0);
        result = 31 * result + (dateOfBirth != null ? dateOfBirth.hashCode() : 0);
        result = 31 * result + (salary != null ? salary.hashCode() : 0);
        return result;
    }
    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", dateOfBirth=" + dateOfBirth +
                ", salary=" + salary +
                '}';
    }
    public long getId() {
        return id;
    }
    public String getName() {
        return name;
    }
    public Date getDateOfBirth() {
        return (Date) dateOfBirth.clone();
    }
    public BigDecimal getSalary() {
        return salary;
    }
    public static final class EmployeeBuilder {
        private long id;
        private String name;
        private Date dateOfBirth;
        private BigDecimal salary;
        private EmployeeBuilder() {
        }
        public static EmployeeBuilder anEmployee() {
            return new EmployeeBuilder();
        }
        public static EmployeeBuilder anEmployee(Employee employee) {
            return anEmployee().withId(employee.getId()).withName(employee.getName()).withDateOfBirth(employee.getDateOfBirth()).withSalary(employee.getSalary());
        }
        public EmployeeBuilder withId(long id) {
            this.id = id;
            return this;
        }
        public EmployeeBuilder withName(String name) {
            this.name = name;
            return this;
        }
        public EmployeeBuilder withDateOfBirth(Date dateOfBirth) {
            this.dateOfBirth = dateOfBirth;
            return this;
        }
        public EmployeeBuilder withSalary(BigDecimal salary) {
            this.salary = salary;
            return this;
        }
        public Employee build() {
            return new Employee(this);
        }
    }
}

Now update the code of the test to see if the HashMap works consistently:
public static void main(String[] args) {
    HashMap<Employee,String> employeeMap = new HashMap<Employee,String>();
    Employee employee1 = Employee.EmployeeBuilder.anEmployee().withId(1)
                                .withName("Sachin")
                                .withDateOfBirth(new Date(1987, 2, 1))
                                .withSalary(new BigDecimal(100000))
                                .build();
    employeeMap.put(employee1,"India");
    for (Map.Entry<Employee, String> employeeStringEntry : employeeMap.entrySet()) {
        System.out.println(employeeStringEntry.getKey().hashCode());
    }
    Employee immutableUpdatedEmployee1 = Employee.EmployeeBuilder.anEmployee(employee1).withName("Rahul").build();
    for (Map.Entry<Employee, String> employeeStringEntry : employeeMap.entrySet()) {
        System.out.println(employeeStringEntry.getKey().hashCode());
    }
    System.out.println(employeeMap.get(immutableUpdatedEmployee1));
    // Returns null
    Employee employee2 = Employee.EmployeeBuilder.anEmployee().withId(1)
            .withName("Sachin")
            .withDateOfBirth(new Date(1987, 2, 1))
            .withSalary(new BigDecimal(100000))
            .build();
    System.out.println(employee2.hashCode());
    System.out.println(employeeMap.get(employee2));
    // Now this works fine and it shall return  the correct object from the HashMap
}

40 Latest Interview Questions and Answers on Spring, Spring MVC, and Spring Boot

  40 Latest Interview Questions and Answers on Spring, Spring MVC, and Spring Boot 1. What is Tight Coupling? When a class (ClassA) is depen...