Interview questions on Collections in java for experienced

 Part 8

Interview questions on Collections in java for experienced covered in this post:


    Interview questions on Collections classes in java for experienced


        What is rehashing?

    -          Hashmap re-size itself by creating a new bucket array of size twice the previous size of hashmap and then start putting all old elements into the new bucket array this process is called rehashing.

     

        Why we need to override hashcode() and equals() in HashMap implementation?

    -          If the two objects are equals by the .equals() method then their hashcode() must be equal. Two equivalent objects have the same hashcode.

    -          If(obj1.equals(obj2)) is true then obj1.hashCode() == obj2.hashCode() always true.

    -          If the two objects are not equal by the .equals() method then the hashcode of the two objects may or may not be equal.

    -          If(!obj1.equals(obj2)) is true then obj1.hashCode() == obj2.hashCode() may be true or may be false.

    -          The objects will be stored in the same bucket which has the same hashcode.

    -          If one bucket has multiple objects then internally it is stored in the form of LinkedList.

    -          If you override the hashcode() method then your object will be placed in the correct bucket and if you override the equals() method then hashmap will check all the keys and if the key exists then it will replace the new value and if the key is not present then that object will be placed next to the current object in the same bucket.

    -          If you don’t override the hashcode() method then your object may place in the wrong bucket.

    -          If you don’t override the equals() method then your object will not place at the correct location.

     

     

    Click here to Purchase on AmazonClick here to Purchase on Amazon

    Click here to Purchase on Amazon

    Note: Please click on Image to Purchase the books from Amazon.in

        What will be the impact if hashcode() method return constant value everytime? What will be the size of hashmap, In Employee class I have overridden equals and hashcode method and hashcode method always return 1. I have 5 employee objects in hashmap. What will be the size?

    -          You would lose any performance given by a hashmap, that can retrieve items from a collection in O(1) time for objects with different hashes, which is what we want to achieve when using HashMaps.

    -          If the equals method is implemented as per the contract and the hashcode method returns a constant value, then we will still be able to retrieve the value for the key from a hashMap, but the performance will be slow compared to the method returning a unique hashcode.

    -          The size would be 5.

     

        What will be the impact if I don't override equals() method?

    -          Only Override HashCode, Use the default Equals: Only the references to the same object will return true. In other words, those objects you expected to be equal will not be equal by calling the equals method.

    -          Only Override Equals, Use the default HashCode: There might be duplicates in the HashMap or HashSet. We write the equals method and expect {"xyz", "XYZ"} to be equals. However, when using a HashMap, they might appear in different buckets, thus the contains() method will not detect each other.

     

        Why String and wrapper classes are considered good keys?

    -          Strings and wrapper classes are immutable so immutable objects are really a good option for keys because once you insert the key’s hashcode never change throughout life.

    -          String and wrapper classes also overrides the equals() and hashcode() methods.

    -          Immutable objects are thread-safe this is an advantage as well.

     

        Can we use ConcurrentHashMap in place of Hashtable?

    -          Yes, definitely we can use ConcurrentHashMap in place of Hashtable.

    -          Concurrent hashmap is more flexible than hashtable.

    -          Hashtable maintains the object level lock.

    -          ConcurrentHashMap maintains the bucket level lock.

     

        Can we use any custom object as a key in HashMap?

    -          We can set any custom object as a key in the hashmap.

    -          You have to override hashcode() and equals() methods into that class.

    -          Please refer to the below example.

    package simplifiedjava.crackedInterview; 

    public class Employee { 

          private String empName;

          private String dept;

          private Double salary;

          private String designation;                 

          public Employee(String empName, String dept, Double salary, String designation) {

                super();

                this.empName = empName;

                this.dept = dept;

                this.salary = salary;

                this.designation = designation;

          }

          public Employee(String empName) {

                this.empName = empName;

          }    

          public String getEmpName() {

                return empName;

          }

          public String getDept() {

                return dept;

          }

          public void setDept(String dept) {

                this.dept = dept;

          } 

          public Double getSalary() {

                return salary;

          }

          public void setSalary(Double salary) {

                this.salary = salary;

          }

          public String getDesignation() {

                return designation;

          }

          public void setDesignation(String designation) {

                this.designation = designation;

          }

          public void setEmpName(String empName) {

                this.empName = empName;

          }

          @Override

          public String toString() {

                return "Employee [empName=" + empName + ", dept=" + dept + ", salary=" + salary + ", designation=" + designation

                            + "]";

          }

          @Override

          public int hashCode() {

                final int prime = 31;

                int result = 1;

                result = prime * result + ((dept == null) ? 0 : dept.hashCode());

                result = prime * result + ((designation == null) ? 0 : designation.hashCode());

                result = prime * result + ((empName == null) ? 0 : empName.hashCode());

                result = prime * result + ((salary == null) ? 0 : salary.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;

                Employee other = (Employee) obj;

                if (dept == null) {

                      if (other.dept != null)

                            return false;

                } else if (!dept.equals(other.dept))

                      return false;

                if (designation == null) {

                      if (other.designation != null)

                            return false;

                } else if (!designation.equals(other.designation))

                      return false;

                if (empName == null) {

                      if (other.empName != null)

                            return false;

                } else if (!empName.equals(other.empName))

                      return false;

                if (salary == null) {

                      if (other.salary != null)

                            return false;

                } else if (!salary.equals(other.salary))

                      return false;

                return true;

          }    

    } 

    package simplifiedjava.crackedInterview; 

    import java.util.HashMap; 

    public class HashMapEmpHashCodeDemo { 

          public static void main(String[] args) {

         HashMap<Employee,Integer> empMap = new HashMap<Employee,Integer>();

         empMap.put(new Employee("Yogesh","IT",100000.00,"System Analyst"),101);

         empMap.put(new Employee("Arpita","Mangement",1200000.00,"Trustee"),102);

         empMap.put(new Employee("Shweta","DevOps",45000.00,"Jenkin Engineer"),103);

         empMap.put(new Employee("Shruti","IT",65000.00,"DB Admin"),104);

         empMap.put(new Employee("Priyanka","IT",35000.00,"Test Engineer"),105);          

         System.out.println(empMap.size());

          }

    }

    Output: 5


     


    • Java interview questions and answers all MNC - Click here
    • Basic core java interview questions and answers for freshers - Click here
    • Core java interview questions for 3 years experience - Click here
    • Core java interview questions and answers for 3-5 years exp - Click here
    • Core java interview questions and Answers for 5 - 7 Years exp - Click here
    • Basic Java Interview Questions and Answers - Click here
    • Java interview questions and answers on oops - Click here
    • Java interview questions and answers on Strings - Click here
    • Java interview questions on exception handling - Click here
    • Interview questions on multithreading in java for experienced - Click here
    • Interview questions on serialization in java for experienced - Click here

    • Interview questions on inner class in java for experienced - Click here
    • Interview questions on Collections in java for experienced - Click here


    Upcoming questions in next post:


    Previous Post                                                                    Next Post



    Thank you techies for visiting this blog. I hope you enjoyed this blog and got more technical knowledge. I have tried to cover all types of questions and provided examples tested on eclipse as much as I can. Guys, please don’t just mug up the questions and answers. Try to clear your concepts with examples. Try to write a code on eclipse once you read the concepts. It will help you to memorize the concepts for a very long time. Simultaneously you will be prepared for interview programs as well. It will help you to survive in the IT sector for a long time. It may be easy to crack an interview but it's really tough to survive in the IT industry with inadequate knowledge and skills. 

    I have collected all the questions from actual interviews attended by my friends, colleagues, college mate and classmate. I have covered frequently asked questions as well as challenging questions. I have included many programs to understand the concept thoroughly. I will try to explain the concept with the help of a real-time program in eclipse. 

    You can share more questions which are not covered in this blog or post. Always welcome your suggestions and queries. I will definitely try to resolve it. 

    Please comment your queries and new set of questions under the comment sections. I will create a new post for those questions. 

    My total experience is 10. Initially I had worked on some support projects and then I moved to java projects. I had worked with many multi-national companies like R-Systems, Tata Consultancy Services, Cybage Softwares.  Fortunately, TCS and Cybage has given me an opportunity to take interviews for experienced candidates. I have conducted more than 1000 interviews by now.

    Mock sessions will be conducted for minimal charges. I will guide you personally on how to crack interviews. All sessions will be online sessions only. My interview book will be provided free of cost if you enroll for personal training. Once you have done practice then I assured you will definitely crack almost all java interviews. 

    I have published my book named with "All MNC Java Interview" which is available on amazon. You can go through it or you can directly contact to me if you are interested to read the book. I will give you special discount. I have covered near about 550 questions and answers with program tested on eclipse and necessary diagram. 

    I have covered interview questions asked in all reputed MNC like TCS, Infosys, Capgemini, Tech Mahindra, Cognizant, City Bank, Barclays, Amdocs, Mindtree etc. My purpose behind this book is, help you to get a job in your dream company. I can understand this is a struggling period for job seekers and freshers. Everybody must have gone from this phase. so never give up. Keep upgrading yourself. I am sure you will get a job in your dream company. All the best!!! 

    Please reach out to me for personal training for interview preparation. 

    You can reach out to me at mncjavainterview@gmail.com.

     



    Post a Comment

    0 Comments