Java Collections interview questions and answers

In this post, I am going to share some of logical Collections interview questions which will help to understand Collections concepts better. For extensive list of java programs, please go to java interview programs.

Question 1:

What can be output of below code :
package org.arpit.java2blog;

import java.util.HashSet;

class Country {
 private String name;
 Country(String name ){
  this.name = name;
 }
 public String toString() {
  return name;
 }
}

public class CollClient {


 public static void main(String[] str) {
  HashSet myMap = new HashSet();
  String s1 = new String("India");
  String s2 = new String("India");
  Country s3 = new Country("France");
  Country s4 = new Country("France");
  myMap.add(s1);
  myMap.add(s2);
  myMap.add(s3);
  myMap.add(s4);
  System.out.println(myMap);
 } 
}

options are : 
A)France France India
B)India India France France
C)India France
D)France France

Answer: A) France France India
Explanation:
As String class overrides hashcode and equals method, it won't allow same string twice in HashSet, but we did not implement hashcode and equals method for Country class, so each object will have different hashcode hence can be inserted in HashSet.

More explanation:
hashcode and equals method in java

Question 2:

package com.org.arpit.java2blog;

import java.util.HashSet;

public class Employee {
 public String name;

 @Override
 public int hashCode() {
  return 31;
 }

 @Override
 public boolean equals(Object obj) {
  return true;
 }

 public static void main(String args[]) {
  Employee employeeOne = new Employee();
  Employee employeeTwo = new Employee();
  employeeOne.name = "John";
  employeeTwo.name = "Martin";
  HashSet<Employee> employeeSet = new HashSet<Employee>();
  employeeSet.add(employeeOne);
  employeeSet.add(employeeTwo);
  System.out.println(employeeSet.size());
 }
}
What will be output of above program:
A. Compilation fails
B. 1
C. 2
D. An Exception is thrown at run time.

Answer: B. 1

Explanation :
As equals method always return true and hashcode return constant as 31.So when you try to put employeeTwo in HashSet, when it will check for equals method, it will always return true, so employeeTwo won't be added to HashSet

More explanation:
hashcode and equals method in java

Question 3:

package com.org.arpit.java2blog;

import java.util.HashSet;

public class Employee {
 public String name;

 @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 (name == null) {
   if (other.name != null)
    return false;
  } else if (!name.equals(other.name))
   return false;
  return true;
 }

 public static void main(String args[]) {
  Employee employeeOne = new Employee();
  Employee employeeTwo = new Employee();
  employeeOne.name = "John";
  employeeTwo.name = "John";
  HashSet<employee> employeeSet = new HashSet<employee>();
  employeeSet.add(employeeOne);
  employeeSet.add(employeeTwo);
  System.out.println(employeeSet.size());
 }
}
What will be output of above program:
A. Compilation fails
B. 1
C. 2
D. An Exception is thrown at run time.

Answer: C.2

Explanation :
As we did not implement hashcode method, each object will have different hashcode(memory address) by default, so employeeTwo will also be added to employeeSet and size of HashSet will be 2

More explanation:
hashcode and equals method in java

Question 4:

package com.org.arpit.java2blog;

import java.util.Iterator;
import java.util.TreeSet;

public class Employee implements Comparable {
 public String name;

 public int compareTo(Object o) {
  return 0;
 }

 public static void main(String args[]) {
  Employee employeeOne = new Employee();
  Employee employeeTwo = new Employee();
  employeeOne.name = "John";
  employeeTwo.name = "Martin";
  TreeSet<Employee> employeeSet = new TreeSet<Employee>();
  employeeSet.add(employeeOne);
  employeeSet.add(employeeTwo);
  Iterator<Employee> empIt = employeeSet.iterator();
  while (empIt.hasNext()) {
   System.out.println(empIt.next().name);
  }
 }
}
What will be output of above program:
A. Martin
B. John
C. John
Martin
D. Compilation fails.
E. The code runs with no output.
F. An exception is thrown at runtime.
Answer: B. John

Explanation :
As you can see we have overridden compareTo method in Employee class and always return 0.
Following steps will take place:
  • First element with "John" will be added to employeeSet.
  • When we will added second element with martin, compareTo method will get called with employeeOne.compareTo(employeeTwo) and it will return 0.
  • As compareTo method returns 0, employeeOne is equals to employeeTwo, so employeeTwo will not be added to treeSet.
  • So output of above program is "John"

More explanation:
TreeSet in java

Question 5:

How to sort a collection of custom Objects in Java?
Answer :
We need to implement comparable interface to custom object class(Lets say Country) and then implement compareTo(Object o) method which will be used for sorting. It will provides default way of sorting custom objects.
If we want to sort custom object (Lets say country) on different attributes such as name,population etc.We can implement Comparator interface and can be used for sorting.
For more details,you can go through following links:

Question 6:

What will be output of below code :
package org.arpit.java2blog;

import java.util.LinkedList;
import java.util.Queue;

public class CollQuestion {
 public static void main(String... args) {
  Queue<String> q = new LinkedList<String>();
  q.add("Delhi");
  q.add("Mumbai");
  q.add("Pune");
  show(q);
 }

 public static void show(Queue q) {
  q.add(new Integer(100));
  while (!q.isEmpty())
   System.out.print(q.poll() + " ");
 }
}
options are:
A)Compile error : Integer can't be added to the queue
B)Delhi Mumbai Pune 100
C)Delhi Mumbai Pune
D)Delhi Mumbai
Correct Answer: B. Delhi Mumbai Pune 100
Explanation:
As show method done not have any generic attached to it, integer can be also added to queue in show method.

Question 7: 

Lets say you have class Employee as below:

package com.org.arpit.java2blog;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Employee {
 public String name;
 public int age;
 
 public Employee(String name, int age) {
  super();
  this.name = name;
  this.age = age;
 }

 public static void main(String args[]) {
  
  List<Employee> employees= new ArrayList<Employee>();
  Employee emp1= new Employee("John",26);
  Employee emp2= new Employee("Martin",23);
  Employee emp3= new Employee("John",20);
  Employee emp4= new Employee("Martin",19);
  Employee emp5= new Employee("Arpit",27);
  
  employees.add(emp1);
  employees.add(emp2);
  employees.add(emp3);
  employees.add(emp4);
  employees.add(emp5);
  System.out.println("List before sorting : ");
  for(Employee e: employees)
  {
   System.out.println(e.name+" - "+e.age);
  }
 }
}
You have list of employees, now you need to sort them on the basis of name then age. It means if names are equals, then sort it by age.
Answer:

Write a anonymous comparator to sort it by name then age.
Collections.sort(employees,new Comparator<Employee>() {

   @Override
   public int compare(Employee o1, Employee o2) {
    // TODO Auto-generated method stub
    if(o1.name.compareTo(o2.name)==0)
    {
     return o1.age - o2.age;
    }
    else
    {
     return o1.name.compareTo(o2.name);
    }
   }
  });
So complete program will be :
package com.org.arpit.java2blog;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Employee {
 public String name;
 public int age;
 
 public Employee(String name, int age) {
  super();
  this.name = name;
  this.age = age;
 }

 public static void main(String args[]) {
  
  List<Employee> employees= new ArrayList<Employee>();
  Employee emp1= new Employee("John",26);
  Employee emp2= new Employee("Martin",23);
  Employee emp3= new Employee("John",20);
  Employee emp4= new Employee("Martin",19);
  Employee emp5= new Employee("Arpit",27);
  
  employees.add(emp1);
  employees.add(emp2);
  employees.add(emp3);
  employees.add(emp4);
  employees.add(emp5);
  System.out.println("List before sorting : ");
  for(Employee e: employees)
  {
   System.out.println(e.name+" - "+e.age);
  }
   
  Collections.sort(employees,new Comparator<Employee>() {

   @Override
   public int compare(Employee o1, Employee o2) {
    // TODO Auto-generated method stub
    if(o1.name.compareTo(o2.name)==0)
    {
     return o1.age - o2.age;
    }
    else
    {
     return o1.name.compareTo(o2.name);
    }
   }
  });
  System.out.println("--------------------------");
  System.out.println("List after sorting : ");
  for(Employee e: employees)
  {
   System.out.println(e.name+" - "+e.age);
  }
 }
 }

When you run able program, you will get below output:
List before sorting : 
John - 26
Martin - 23
John - 20
Martin - 19
Arpit - 27
--------------------------
List after sorting : 
Arpit - 27
John - 20
John - 26
Martin - 19
Martin - 23

Question 8:

How HashMap works in java

I will recommend you to go to How HashMap works in java to understand it better.

Question 9:

package com.org.arpit.java2blog;

import java.util.HashSet;

public class Employee {
 public String name;

 @Override
 public int hashCode() {
  return 31;
 }

 public static void main(String args[]) {
  Employee employeeOne = new Employee();
  Employee employeeTwo = new Employee();
  employeeOne.name = "John";
  employeeTwo.name = "John";
  HashSet<Employee> employeeSet = new HashSet<Employee>();
  employeeSet.add(employeeOne);
  employeeSet.add(employeeTwo);
  System.out.println(employeeSet.size());
 }
}
What will be output of above program:
A. Compilation fails
B. 1
C. 2
D. An Exception is thrown at run time.

Answer: C. 2

Explanation :
As we did not override equals method here, it will have default implementation which return true if objects point to same reference (==) but here, as we have created two different object as employeeOne and employeeTwo, size of HashSet will be 2

More explanation:
hashcode and equals method in java

Question 10:

Difference between Comparator and Comparable in java?

Answer: It is one of favourite question of interviewer on Collections framework. Please go to difference between comparator and comparable for differences.

Please go through java interview programs for more such programs and core java interview questions for more interview questions.


Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012