Skip to main content

Collection



1. How does HashMap work in Java?


2. What is the difference between poll() and remove() method of Queue interface? (answer)
Though both poll() and remove() method from Queue is used to remove the object and returns the head of the queue, there is a subtle difference between them. If Queue is empty() then a call to remove() method will throw Exception, while a call to poll() method returns null. By the way, exactly which element is removed from the queue depends upon queue's ordering policy and varies between different implementation, for example, PriorityQueue keeps the lowest element as per Comparator or Comparable at head position. 


3. What is the difference between fail-fast and fail-safe Iterators?

5. What is the difference between Synchronized Collection and Concurrent Collection? (answer)
Java 5 has added several new Concurrent Collection classes e.g.ConcurrentHashMapCopyOnWriteArrayListBlockingQueue etc.Java Also provided a way to get Synchronized copy of collection e.g. ArrayList, HashMap by usingCollections.synchronizedMap() Utility function. One Significant difference is that Concurrent Collections has better performance than synchronized Collection because they lock only a portion of Map to achieve concurrency and Synchronization.


6. What is the difference between Iterator and Enumeration? (answer)
This is a beginner level collection interview questions and mostly asked during interviews of Junior Java developer up to experience of 2 to 3 years Iterator duplicate functionality of Enumeration with one addition of remove() method and both provide navigation functionally on objects of Collection.Another difference is that Iterator is more safe than Enumeration and doesn't allow another thread to modify collection object during iteration except remove() method and throwsConcurrentModificaitonException. See Iterator vs Enumeration in Java for more differences.



7. How does HashSet is implemented in Java, How does it use Hashing? (answer)
This is a tricky question in Java because for hashing you need both key and value and there is no key for the store it in a bucket, then how exactly HashSetstore element internally. Well, HashSet is built on top of HashMap. If you look at source code of java.util.HashSet class, you will find that that it uses a HashMap with same values for all keys, as shown below:

private transient HashMap map;

// Dummy value to associate with an Object in the backing Map

private static final Object PRESENT = new Object();

When you call 
add() method of HashSet, it put entry in HashMap :

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

Since keys are unique in a HashMap, it provides uniqueness guarantee of Set interface.
9. The difference between HashMap and Hashtable?
.
10. When do you use ConcurrentHashMap in Java? (answer)
This is another advanced level collection interview questions in Java which normally asked to check whether the interviewer is familiar with optimization done onConcurrentHashMap or not. ConcurrentHashMap is better suited for situation where you have multiple readers and one
Writer or fewer writers since Map gets locked only during the write operation. If you have an equal number of reader and writer than ConcurrentHashMap will perform in the line of Hashtable or synchronized HashMap.

11. What is the difference between Set and List in Java? (
answer)
Another classical Java Collection interviews popular on telephonic round or the first round of interview. Most of Java programmer knows that Set doesn't allowed duplicate while List does and List maintains insertion order while Set doesn't. What is key here is to show the interviewer that you can decide which collection is more suited based on requirements.




What is the difference between Hashtable and ConcurrentHashMap in Java?
What is the difference between Vector and ArrayList in Java?
Can you write code to traverse Map in Java on 4 ways?
What is the difference between ArrayList and LinkedList in Java?

How do you find if ArrayList contains duplicates or not?
Ans: Here are five ways we can check if an array has duplicates or not: 

1) brute force method which compares each element of Array to all other elements and returns true if it founds duplicates. Though this is not an efficient choice it is the one which first comes to mind.

2) Another quick way of checking if a Java array contains duplicates or not is to convert that array into Set. Since Set doesn’t allow duplicates size of  the corresponding Set will be smaller than original Array if Array contains duplicates otherwise the size of both Array and Set will be same.

3) One more way to detect duplication in java array is adding every element of the array into HashSet which is a Set implementation. Since the add(Object obj) method of Set returns false if Set already contains an element to be added, it can be used to find out if the array contains duplicates in Java or not.


 Which two method you need to implement for key Object in HashMap ?
In order to use any object as Key in HashMap, it must implements equals and hashcode method in Java.


Comments

Popular posts from this blog

Mockito interview Questions

1.       Question 1. What Is Mockito? Answer : Mockito allows creation of mock object for the purpose of Test Driven Development and Behavior Driven development. Unlike creating actual object, Mockito allows creation of fake object (external dependencies) which allows it to give consistent results to a given invocation. 2.       Question 2. Why Do We Need Mockito? What Are The Advantages? Answer : Mockito differentiates itself from the other testing framework by removing the expectation beforehand. So, by doing this, it reduces the coupling. Most of the testing framework works on the "expect-run-verify". Mockito allows it to make it "run-verify" framework. Mockito also provides annotation which allows to reduce the boilerplate code. 3.       Question 3. Can You Explain A Mockito Framework? Answer : In Mockito, you always check a particular class. The dependency in that class is injected using m...

JAVA Expert Interview Questions Answers 2017

Java Basics ::  Interview Questions and Answers Home  »  Interview Questions  »  Technical Interview  »  Java Basics  » Interview Questions 1.     What is the difference between a constructor and a method? A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator. A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator. 2.     What is the purpose of garbage collection in Java, and when is it used? The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used. 3.  ...

Java Example Program to Convert List to Set

import java.util.ArrayList; import java.util.HashSet; import java.util.Set; public class ListToSet {  /**   * @author Amarjit Kumar   * @category interview questions   *   * Description: Convert List to set in java with example program   *   */  public static void main(String[] args) {   ArrayList<String> arrList= new ArrayList<>();   arrList.add("Java");   arrList.add("Java");   arrList.add("List to String");   arrList.add("Example Program");   Set<String> strSet = new HashSet<String>(arrList);   System.out.println(strSet);   System.out.println(arrList);  } } /*  * Java program to convert list to set. Convert ArrayList of string to HashSet  * in java example program How to convert List to Set in java Set<String> strSet  * = new HashSet<String>(arrList); HashSet having a constructor which will take  * list as an ar...