Useful java collection interview questions

Without argument, java collections is one of the most important area where you will be tested in any position whether junior or senior. The scope is so much wide, that its almost impossible to cover all the questions. Yet based on my previous interviews, I am attempting to put as many as possible GOOD java collection interview questions you must know.

I am aiming both beginners and senior level questions, so bear with me if you found some questions too basic because they might be useful for some junior developers.

Questions in this post:

General questions

1) What is the Java Collections API? List down its advantages?
2) Explain Collections hierarchy?
3) Why Collection interface does not extend Cloneable and Serializable interface?
4) Why Map interface does not extend Collection interface?

List interface related

5) Why we use List interface? What are main classes implementing List interface?
6) How to convert an array of String to ArrayList?
7) How to reverse the list?

Set interface related

8) Why we use Set interface? What are main classes implementing Set interface?
9) How HashSet store elements?
10) Can a null element added to a TreeSet or HashSet?

Map interface related

11) Why we use Map interface? What are main classes implementing Map interface?
12) What are IdentityHashMap and WeakHashMap?
13) Explain ConcurrentHashMap? How it works?
14) How hashmap works?
15) How to design a good key for hashmap?
16) What are different Collection views provided by Map interface?
17) When to use HashMap or TreeMap?

Tell the difference questions

18) Difference between Set and List?
19) Difference between List and Map?
20) Difference between HashMap and HashTable?
21) Difference between Vector and ArrayList?
22) Difference between Iterator and Enumeration?
23) Difference between HashMap and HashSet?
24) Difference between Iterator and ListIterator?
25) Difference between TreeSet and SortedSet?
26) Difference between ArrayList and LinkedList?

More questions

27) How to make a collection read only?
28) How to make a collection thread safe?
29) Why there is not method like Iterator.add() to add elements to the collection?
30) What are different ways to iterate over a list?
31) What do you understand by iterator fail-fast property?
32) What is difference between fail-fast and fail-safe?
33) How to avoid ConcurrentModificationException while iterating a collection?
34) What is UnsupportedOperationException?
35) Which collection classes provide random access of it’s elements?
36) What is BlockingQueue?
37) What is Queue and Stack, list their differences?
38) What is Comparable and Comparator interface?
39) What are Collections and Arrays class?
40) Recommended resources

Without wasting time, let dig into concepts.

General question

1) What is the Java Collection framework? List down its advantages?

By definition, a collection is an object that represents a group of objects. Like in set theory, a set is group of elements. Easy enough !!
Prior to JDK 1.2, JDK has some utility classes such as Vector and HashTable, but there was no concept of Collection framework. Later from JDK 1.2 onwards, JDK felt the need of having a consistent support for reusable data structures. Finally, the collections framework was designed and developed primarily by Joshua Bloch, and was introduced in JDK 1.2.

Its most noticeable advantages can be listed as:

  • Reduced programming effort due to ready to use code
  • Increased performance because of high-performance implementations of data structures and algorithms
  • Provides interoperability between unrelated APIs by establishing a common language to pass collections back and forth
  • Easy to learn APIs by learning only some top level interfaces and supported operations

2) Explain Collection’s hierarchy?
Java Collection Hierarchy

Java Collection Hierarchy

As shown in above image, collection framework has one interface at top i.e. Collection. It is extended by Set, List and Queue interfaces. Then there are loads of other classes in these 3 branches which we will learn in following questions.

Remember the signature of Collection interface. It will help you in many question.

public interface Collection extends Iterable {
//method definitions
}

Framework also consist of Map interface, which is part of collection framework. but it does not extend Collection interface. We will see the reason in 4th question in this question bank.

3) Why Collection interface does not extend Cloneable and Serializable interface?

Well, simplest answer is “there is no need to do it“. Extending an interface simply means that you are creating a subtype of interface, in other words a more specialized behavior and Collection interface is not expected to do what Cloneable and Serializable interfaces do.

Another reason is that not everybody will have a reason to have Cloneable collection because if it has very large data, then every unnecessary clone operation will consume a big memory. Beginners might use it without knowing the consequences.

Another reason is that Cloneable and Serializable are very specialized behavior and so should be implemented only when required. For example, many concrete classes in collection implement these interfaces. So if you want this feature. use these collection classes otherwise use their alternative classes.

4) Why Map interface does not extend Collection interface?

A good answer to this interview question 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.

Due to such big differences, Collection interface was not used in Map interface, and it was build in separate hierarchy.

List interface related

5) Why we use List interface? What are main classes implementing List interface?

A java list is a “ordered” collection of elements. This ordering is a zero based index. It does not care about duplicates. Apart from methods defined in Collection interface, it does have its own methods also which are largely to manipulate the collection based on index location of element. These methods can be grouped as search, get, iteration and range view. All above operations support index locations.

The main classes implementing List interface are: Stack, Vector, ArrayList and LinkedList. Read more about them in java documentation.

6) How to convert an array of String to arraylist?

This is more of a programmatic question which is seen at beginner level. The intent is to check the knowledge of applicant in Collection utility classes. For now, lets learn that there are two utility classes in Collection framework which are mostly seen in interviews i.e. Collections and Arrays.

Collections class provides some static functions to perform specific operations on collection types. And Arrays provide utility functions to be performed on array types.

//String array
String[] words = {"ace", "boom", "crew", "dog", "eon"};
//Use Arrays utility class
List wordList = Arrays.asList(words);
//Now you can iterate over the list

Please not that this function is not specific to String class, it will return List of element of any type, of which the array is. e.g.

//String array
Integer[] nums = {1,2,3,4};
//Use Arrays utility class
List numsList = Arrays.asList(nums);

7) How to reverse the list?

This question is just like above to test your knowledge of Collections utility class. Use it reverse() method to reverse the list.

	Collections.reverse(list);

Set interface related

8) Why we use Set interface? What are main classes implementing Set interface?

It models the mathematical set in set theory. Set interface is like List interface but with some differences. First, it is not ordered collection. So no ordering is preserved while adding or removing elements. The main feature it does provide is “uniqueness of elements“. It does not support duplicate elements.

Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ. Two Set instances are equal if they contain the same elements.

Based on above reasons, it does not have operations based on indexes of elements like List. It only has methods which are inherited by Collection interface.

Main classes implementing Set interface are : EnumSet, HashSet, LinkedHashSet, TreeSet. Read more on related java documentation.

9) How HashSet store elements?

You must know that HashMap store key-value pairs, with one condition i.e. keys will be unique. HashSet uses Map’s this feature to ensure uniqueness of elements. In HashSet class, a map declaration is as below:

private transient HashMap<E,Object> map;

//This is added as value for each key
private static final Object PRESENT = new Object();

So when you store a element in HashSet, it stores the element as key in map and “PRESENT” object as value. (See declaration above).

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

I will highly suggest you to read this post: How HashMap works in java? This post will help you in answering all the HashMap related questions very easily.

10) Can a null element added to a TreeSet or HashSet?

As you see, There is no null check in add() method in previous question. And HashMap also allows one null key, so one “null” is allowed in HashSet.

TreeSet uses the same concept as HashSet for internal logic, but uses NavigableMap for storing the elements.

private transient NavigableMap<E,Object> m;

// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();

NavigableMap is subtype of SortedMap which does not allow null keys. So essentially, TreeSet also does not support null keys. It will throw NullPointerException if you try to add null element in TreeSet.

Map interface related

11) Why we use Map interface? What are main classes implementing Map interface?

Map interface is a special type of collection which is used to store key-value pairs. It does not extend Collection interface for this reason. This interface provides methods to add, remove, search or iterate over various views of Map.

Main classes implementing Map interface are: HashMap, Hashtable, EnumMap, IdentityHashMap, LinkedHashMap and Properties.

12) What are IdentityHashMap and WeakHashMap?

IdentityHashMap is similar to HashMap except that it uses reference equality when comparing elements. IdentityHashMap class is not a widely used Map implementation. While this class implements the Map interface, it intentionally violates Map’s general contract, which mandates the use of the equals() method when comparing objects. IdentityHashMap is designed for use only in the rare cases wherein reference-equality semantics are required.

WeakHashMap is an implementation of the Map interface that stores only weak references to its keys. Storing only weak references allows a key-value pair to be garbage collected when its key is no longer referenced outside of the WeakHashMap. This class is intended primarily for use with key objects whose equals methods test for object identity using the == operator. Once such a key is discarded it can never be recreated, so it is impossible to do a look-up of that key in a WeakHashMap at some later time and be surprised that its entry has been removed.

13) Explain ConcurrentHashMap? How it works?

Taking from java docs:

A hash table supporting full concurrency of retrievals and adjustable expected concurrency for updates. This class obeys the same functional specification as Hashtable, and includes versions of methods corresponding to each method of Hashtable. However, even though all operations are thread-safe, retrieval operations do not entail locking, and there is not any support for locking the entire table in a way that prevents all access. This class is fully interoperable with Hashtable in programs that rely on its thread safety but not on its synchronization details.

Read more about how concurrent hashmap works and related interview questions.

14) How hashmap works?

The most important question which is most likely to be seen in every level of job interviews. You must be very clear on this topic., not only because it is most asked question but also it will open up your mind in further questions related to collection APIs.

Answer to this question is very large and you should read it my post: How HashMap works? For now, lets remember that HashMap works on principle of Hashing. A map by definition is : “An object that maps keys to values”. To store such structure, it uses an inner class Entry:

static class Entry implements Map.Entry
{
final K key;
V value;
Entry next;
final int hash;
...//More code goes here
}

Here key and value variables are used to store key-value pairs. Whole entry object is stored in an array.

/**
* The table, re-sized as necessary. Length MUST Always be a power of two.
*/
transient Entry[] table;

The index of array is calculated on basis on hashcode of Key object. Read more of linked topic.

15) How to design a good key for hashmap?

Another good question usually followed up after answering how hashmap works. Well, the most important constraint is you must be able to fetch the value object back in future. Otherwise, there is no use of having such a data structure. If you understand the working of hashmap, you will find it largely depends on hashCode() and equals() method of Key objects.

So a good key object must provide same hashCode() again and again, no matter how many times it is fetched. Similarly, same keys must return true when compare with equals() method and different keys must return false.

For this reason, immutable classes are considered best candidate for HashMap keys.

Read more : How to design a good key for HashMap?

16) What are different Collection views provided by Map interface?

Map interface provides 3 views of key-values pairs stored in it:

  • key set view
  • value set view
  • entry set view

All the views can be navigated using iterators.

17) When to use HashMap or TreeMap?

HashMap is well known class and all of us know that. So, I will leave this part by saying that it is used to store key-value pairs and allows to perform many operations on such collection of pairs.

TreeMap is special form of HashMap. It maintains the ordering of keys which is missing in HashMap class. This ordering is by default “natural ordering”. The default ordering can be override by providing an instance of Comparator class, whose compare method will be used to maintain ordering of keys.

Please note that all keys inserted into the map must implement the Comparable interface (this is necessary to decide the ordering). Furthermore, all such keys must be mutually comparable: k1.compareTo(k2) must not throw a ClassCastException for any keys k1 and k2 in the map. If the user attempts to put a key into the map that violates this constraint (for example, the user attempts to put a string key into a map whose keys are integers), the put(Object key, Object value) call will throw a ClassCastException.

Tell the difference questions

18) Difference between Set and List?

The most noticeable differences are :

  • Set is unordered collection where List is ordered collection based on zero based index.
  • List allow duplicate elements but Set does not allow duplicates.
  • List does not prevent inserting null elements (as many you like), but Set will allow only one null element.

19) Difference between List and Map?

Perhaps most easy question. List is collection of elements where as map is collection of key-value pairs. There is actually lots of differences which originate from first statement. They have separate top level interface, separate set of generic methods, different supported methods and different views of collection.

I will take much time hear as answer to this question is enough as first difference only.

20) Difference between HashMap and HashTable?

There are several differences between HashMap and Hashtable in Java:

  • Hashtable is synchronized, whereas HashMap is not.
  • Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.
  • The third significant difference between HashMap vs Hashtable is that Iterator in the HashMap is a fail-fast iterator while the enumerator for the Hashtable is not.

21) Difference between Vector and ArrayList?

Lets note down the differences:

  • All the methods of Vector is synchronized. But, the methods of ArrayList is not synchronized.
  • Vector is a Legacy class added in first release of JDK. ArrayList was part of JDK 1.2, when collection framework was introduced in java.
  • By default, Vector doubles the size of its array when it is re-sized internally. But, ArrayList increases by half of its size when it is re-sized.

22) Difference between Iterator and Enumeration?

Iterators differ from enumerations in three ways:

  • Iterators allow the caller to remove elements from the underlying collection during the iteration with its remove() method. You can not add/remove elements from a collection when using enumerator.
  • Enumeration is available in legacy classes i.e Vector/Stack etc. whereas Iterator is available in all modern collection classes.
  • Another minor difference is that Iterator has improved method names e.g. Enumeration.hasMoreElement() has become Iterator.hasNext(), Enumeration.nextElement() has become Iterator.next() etc.

23) Difference between HashMap and HashSet?

HashMap is collection of key-value pairs whereas HashSet is un-ordered collection of unique elements. That’s it. No need to describe further.

24) Difference between Iterator and ListIterator?

There are three Differences are there:

  • We can use Iterator to traverse Set and List and also Map type of Objects. But List Iterator can be used to traverse for List type Objects, but not for Set type of Objects.
  • By using Iterator we can retrieve the elements from Collection Object in forward direction only whereas List Iterator, which allows you to traverse in either directions using hasPrevious() and previous() methods.
  • ListIterator allows you modify the list using add() remove() methods. Using Iterator you can not add, only remove the elements.

25) Difference between TreeSet and SortedSet?

SortedSet is an interface which TreeSet implements. That’ it !!

26) Difference between ArrayList and LinkedList?
  • LinkedList store elements within a doubly-linked list data structure. ArrayList store elements within a dynamically resizing array.
  • LinkedList allows for constant-time insertions or removals, but only sequential access of elements. In other words, you can walk the list forwards or backwards, but grabbing an element in the middle takes time proportional to the size of the list. ArrayLists, on the other hand, allow random access, so you can grab any element in constant time. But adding or removing from anywhere but the end requires shifting all the latter elements over, either to make an opening or fill the gap.
  • LinkedList has more memory overhead than ArrayList because in ArrayList each index only holds actual object (data) but in case of LinkedList each node holds both data and address of next and previous node.

More questions

27) How to make a collection read only?

Use following methods:

  • Collections.unmodifiableList(list);
  • Collections.unmodifiableSet(set);
  • Collections.unmodifiableMap(map);

These methods takes collection parameter and return a new read-only collection with same elements as in original collection.

28) How to make a collection thread safe?

Use below methods:

  • Collections.synchronizedList(list);
  • Collections.synchronizedSet(set);
  • Collections.synchronizedMap(map);

Above methods take collection as parameter and return same type of collection which are synchronized and thread safe.

29) Why there is not method like Iterator.add() to add elements to the collection?

The sole purpose of an Iterator is to enumerate through a collection. All collections contain the add() method to serve your purpose. There would be no point in adding to an Iterator because the collection may or may not be ordered. And add() method can not have same implementation for ordered and unordered collections.

30) What are different ways to iterate over a list?

You can iterate over a list using following ways:

  • Iterator loop
  • For loop
  • For loop (Advance)
  • While loop

Read more : http://www.mkyong.com/java/how-do-loop-iterate-a-list-in-java/

31) What do you understand by iterator fail-fast property?

Fail-fast Iterators fail as soon as they realized that structure of Collection has been changed since iteration has begun. Structural changes means adding, removing or updating any element from collection while one thread is Iterating over that collection.

Fail-fast behavior is implemented by keeping a modification count and if iteration thread realizes the change in modification count it throws ConcurrentModificationException.

32) What is difference between fail-fast and fail-safe?

You have understood fail-fast in previous question. Fail-safe iterators are just opposite to fail-fast. They never fail if you modify the underlying collection on which they are iterating, because they work on clone of Collection instead of original collection and that’s why they are called as fail-safe iterator.

Iterator of CopyOnWriteArrayList is an example of fail-safe Iterator also iterator written by ConcurrentHashMap keySet is also fail-safe iterator and never throw ConcurrentModificationException.

33) How to avoid ConcurrentModificationException while iterating a collection?

You should first try to find another alternative iterator which are fail-safe. For example if you are using List and you can use ListIterator. If it is legacy collection, you can use enumeration.

If above options are not possible then you can use one of three changes:

  • If you are using JDK1.5 or higher then you can use ConcurrentHashMap and CopyOnWriteArrayList classes. It is the recommended approach.
  • You can convert the list to an array and then iterate on the array.
  • You can lock the list while iterating by putting it in a synchronized block.

Please note that last two approaches will cause a performance hit.

34) What is UnsupportedOperationException?

This exception is thrown on invoked methods which are not supported by actual collection type.

For example, if you make a read-only list list using “Collections.unmodifiableList(list)” and then call add() or remove() method, what should happen. It should clearly throw UnsupportedOperationException.

35) Which collection classes provide random access of it’s elements?

ArrayList, HashMap, TreeMap, Hashtable classes provide random access to it’s elements.

36) What is BlockingQueue?

A Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.

BlockingQueue methods come in four forms: one throws an exception, the second returns a special value (either null or false, depending on the operation), the third blocks the current thread indefinitely until the operation can succeed, and the fourth blocks for only a given maximum time limit before giving up.

Read the example usage of blocking queue in post : How to use blocking queue?

37) What is Queue and Stack, list down their differences?

A collection designed for holding elements prior to processing. Besides basic Collection operations, queues provide additional insertion, extraction, and inspection operations.
Queues typically, but do not necessarily, order elements in a FIFO (first-in-first-out) manner.

Stack is also a form of Queue but one difference, it is LIFO (last-in-first-out).

Whatever the ordering used, the head of the queue is that element which would be removed by a call to remove() or poll(). Also note that Stack and Vector are both synchronized.

Usage: Use a queue if you want to process a stream of incoming items in the order that they are received.Good for work lists and handling requests.
Use a stack if you want to push and pop from the top of the stack only. Good for recursive algorithms.

38) What is Comparable and Comparator interface?

In java. all collection which have feature of automatic sorting, uses compare methods to ensure the correct sorting of elements. For example classes which use sorting are TreeSet, TreeMap etc.

To sort the data elements a class needs to implement Comparator or Comparable interface. That’s why all Wrapper classes like Integer,Double and String class implements Comparable interface.

Comparable helps in preserving default natural sorting, whereas Comparator helps in sorting the elements in some special required sorting pattern. The instance of comparator if passed usually as collection’s constructor argument in supporting collections.

39) What are Collections and Arrays classes?

Collections and Arrays classes are special utility classes to support collection framework core classes. They provide utility functions to get read-only/ synchronized collections, sort the collection on various ways etc.

Arrays also helps array of objects to convert in collection objects. Arrays also have some functions which helps in copying or working in part of array objects.

40) Recommended resources

Well it is not interview question.. :-). This is only for fun. But you should really read my blog for more posts on collection framework knowledge.

I hope these java collection interview questions will help in in your next interview. Further, I will suggest you to read more on above questions apart from this post. A more knowledge will only help you.

Happy Learning !!

66 thoughts on “Useful java collection interview questions”

  1. Que no :10
    TreeSet allows one null element…you are saying it does not support null value…actully if wetry to add second null vlaue then only it gives null pinter exception….adding one null value works perfectly fine

    1. Run below simple program:

      public static void main(String[] args)
         {
            TreeSet<String> set = new TreeSet<String>();
            set.add(null);
         }
      

      It gives error as : Exception in thread “main” java.lang.NullPointerException
      at java.util.TreeMap.compare(Unknown Source)
      at java.util.TreeMap.put(Unknown Source)
      at java.util.TreeSet.add(Unknown Source)

      I have made bold the TreeMap.compare() which is internally used inside TreeSet for maintaining the ordering. Null simply do not fit in any sorting order, so they are restricted.

    2. Tree map doesn’t allow any null value as key whereas hash map allow one null value as key because tree map use sorted set to maintain order of key

  2. Hi Lokesh,

    I really like your posts.I want you to post one more interview question with answer which i faced recently in an interview :

    How Collections.sort works? means which sorting algorithm does it implement?

    A

  3. Hi Gupta,

    I am afraid there is a correction needed at 7th question. I guess, sorting list in reverse order and reversing the list order are different.

    reverse() will just reverse the order. It will not sort.

    The answer for this question should be,

    Collections.sort(list, Collections.reverseOrder());

    If you have meant only to reverse the order, you have mislead me ;) Let me know what you think.

    Thanks for the post! It is really good. Keep going!

    – Raja

  4. Hi Lokesh i solved above problem, running perfectly!

    package com.intuit;

    class Shared{
    private boolean done=false;
    protected int[] even={2,4,6,8,10};
    protected int[] odd={1,3,5,7,9};
    private static int i=0;
    private static int j=0;
    public synchronized void printOdd(){
    while(done){
    try{
    wait();
    }catch(InterruptedException ie){

    }
    }
    if(j!=odd.length)
    System.out.println(odd[j++]);
    done=true;
    notify();
    }
    public synchronized void printEven(){
    while(!done){
    try{
    wait();
    }catch(InterruptedException ie){

    }
    }
    if(i!=even.length)
    System.out.println(even[i++]);
    done=false;
    notify();
    }
    }
    class OddThread implements Runnable{
    private Shared shared;
    public OddThread(Shared shared){
    this.shared=shared;
    }
    public void run(){
    for(int i=0;i<=shared.odd.length;i++){
    shared.printOdd();
    }
    }
    }
    class EvenThread implements Runnable{
    private Shared shared;
    public EvenThread(Shared shared){
    this.shared=shared;
    }
    public void run(){
    for(int i=0;i<shared.even.length;i++){
    shared.printEven();
    }
    }
    }
    public class OddEvenThread {

    public static void main(String[] args) {
    Shared shared = new Shared();
    Thread t1 = new Thread(new OddThread(shared));
    Thread t2 = new Thread(new EvenThread(shared));
    t1.start();
    t2.start();

    try{
    Thread.sleep(1000);
    }catch(InterruptedException ie){

    }
    }
    }

      1. Hi , In which scenario we use Singly Linked list data structure and double linked list? Under what circumstance Singly linked list data structure will be better then double linked list?

        1. A real good question. Surjeet, I never came across any situation where I was forced to use (or even suggested to use) doubly linked list. In my whole career, I always managed to do my work with simple data structures like stack, linked list and maps.
          I will really like to get some good answers from all those who visited and read this thread.

  5. Hi Lokesh, recently i hv faced 1 interview in Intuit company, they asked “There are two threads, first thread contains even number(2,4,6,8,10) and second thread contains odd number(1,3,5,7,9), and i want to print in natural order or sequence like 1,2,3,4,5,6,7,8,9,10″ , i answered we could use wait and notify method, after first thread put odd number and will notify to second thread that will print even number, and it will continue to till it both threads prints in natural order. but he was not satisfied, let me know if u could provide solution

      1. Another Question i hv faced::::

        Say there are 3 array lists l1, l2 & l3 of same length.
        Three threads accessing three lists. Say T1 -> l1, T2 ->l2 & T3 ->l3.
        It should print in the order say first element of 1st then first element of 2nd list and
        then first element of 3rd list.
        Then second element of 1st then second element of 2nd list and then second element of 3rd list?

        well i knw here i hv to use wait and notify…How to approach?
        any suggestion

        1. A good solution can be using Semaphore. Read more about Semaphore here: http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Semaphore.html

          A working example is below:

          package com.howtodoinjava.demo.rest;

          import java.util.Arrays;
          import java.util.List;
          import java.util.concurrent.Semaphore;

          public class PrintList {
          private List list1 = Arrays.asList(new Integer[]{1,2,3,4,5});
          private List
          list2 = Arrays.asList(new Integer[]{1,2,3,4,5});
          private List
          list3 = Arrays.asList(new Integer[]{1,2,3,4,5});
          private int listSize = 5;

          private Semaphore semaphore = null;

          public PrintList() {
          semaphore = new Semaphore(3);
          }

          public void print() throws InterruptedException{
          semaphore.acquire();
          for(int i = 0;i System.out.println(list1.get(i));
          System.out.println(list2.get(i));
          System.out.println(list3.get(i));
          }
          semaphore.release();
          }

          public static void main(String[] args) {
          final PrintList printList = new PrintList();
          Runnable runnable = new Runnable() {

          @Override
          public void run() {
          try {
          printList.print();
          } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
          }
          }
          };

          Thread t1 = new Thread(runnable);
          Thread t2 = new Thread(runnable);
          Thread t3 = new Thread(runnable);
          t1.start();t2.start();t3.start();
          }

          }

          1. semaphore.acquire();
            for(int i = 0;i<listSize;i++){
            System.out.println(list1.get(i));
            System.out.println(list2.get(i));
            System.out.println(list3.get(i));
            }
            semaphore.release();

            But here the above code:each of the thread is accessing three list???

        2. Hi Surjeet, Could you please share the full code in both the approaches like using wait() and notify() methods and also using Semaphore.

  6. Hi Lokesh,
    For reversing the list you have suggested to use:

    List reversedList = Collections.reverse(list);

    As return type of Collections.reverse(list) is a void we will not be able to compile the above piece of code.

  7. Hi Lokesh,

    Is it correct?
    18) Difference between Set and List?
    3rd point states that “List does not prevent inserting null elements (as many you like), but Set will allow only one null element.”

    TreeSet does not allow to add one null element.
    It throws NullPointerException.

    Sample Code:
    Set s1 = new TreeSet();
    s1.add(null);

    Output:
    Exception in thread “main” java.lang.NullPointerException
    at java.util.TreeMap.compare(Unknown Source)
    at java.util.TreeMap.put(Unknown Source)
    at java.util.TreeSet.add(Unknown Source)

    1. Really a very good question. I can’t think of any (good) reason for wanting to store null as a key, and in general I will advise against using null as a key. Taking from JDK 1.2 Java Collections API Change Summary:


      Added null-key support to HashMap
      . This was done for consistency with TreeMap and the late, unlamented ArrayMap, and because customers requested it. Now all of our general-purpose collection implementations accept null keys, values and elements.

      Later Doug Lea also agreed that it is not a good design. http://cs.oswego.edu/pipermail/concurrency-interest/2006-May/002485.html

      Further digressing: I personally think that allowing nulls in Maps (also Sets) is an open invitation for programs to contain errors that remain undetected until they break at just the wrong time.

      1. I want to get the highest occurring entry data element. I want to store my data in HashMap so that I can get the element with maximum occurrence.

        Can you suggest some alternative approach.

        Thanks in Advance.

  8. I have One Question related to List :
    How to remove particular value from the List ?
    Suppose I have List and it contain [0,1,2,3,4,5] then i want to remove 1 value from the list ?
    How it possible

  9. Hi Lokesh,
    Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection?
    Explain me with an example

  10. Hi Lokesh,
    how can i implement this example
    class Contact{
    String name;
    String email;
    String mobile no;
    }
    static HashMap convertToMap(List list{
    //how to write logic in here
    }

    Thank’s in advance

        1. Hi Lokesh,
          Thanks for encourage me, i tried this program but this is correct or not
          package com.pvr;

          import java.util.ArrayList;
          import java.util.HashMap;
          import java.util.List;
          import java.util.Map;

          public class Contact {
          private int id;
          private String name;
          private String email;
          private String address;

          public int getId() {
          return id;
          }

          public void setId(int id) {
          this.id = id;
          }

          public String getName() {
          return name;
          }

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

          public String getEmail() {
          return email;
          }

          public void setEmail(String email) {
          this.email = email;
          }

          public String getAddress() {
          return address;
          }

          public void setAddress(String address) {
          this.address = address;
          }

          public Contact() {
          }
          public Contact(int id,String name,String email,String address){
          this.id=id;
          this.name=name;
          this.email=email;
          this.address=address;
          }
          static HashMap convertToMap(List list){
          Map map=new HashMap();
          for(Contact c:list){
          map.put(c.toString(),c);
          }
          return (HashMap) map;

          }
          public static void main(String[] args){
          List list=new ArrayList();
          list.add(new Contact(101,”pvr”, “pvr@email.com”,”gnt”));
          list.add(new Contact(102,”ven”,”ven@gmail.com”,”hyd”));
          HashMap m=new Contact().convertToMap(list);
          System.out.println(m);
          }
          }

          1. import java.util.ArrayList;
            import java.util.HashMap;
            import java.util.List;
            import java.util.Map;

            public class Contact
            {
            private int id;
            private String name;
            private String email;
            private String address;

            public int getId() {
            return id;
            }

            public void setId(int id) {
            this.id = id;
            }

            public String getName() {
            return name;
            }

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

            public String getEmail() {
            return email;
            }

            public void setEmail(String email) {
            this.email = email;
            }

            public String getAddress() {
            return address;
            }

            public void setAddress(String address) {
            this.address = address;
            }

            @Override
            public String toString() {
            return "Contact#" + this.getId();
            }
            public Contact(int id, String name, String email, String address) {
            this.id = id;
            this.name = name;
            this.email = email;
            this.address = address;
            }

            private static Map convertToMap(List list) {
            Map map = new HashMap();
            for (Contact c : list) {
            map.put(c.getId(), c);
            }
            return map;
            }

            public static void main(String[] args){
            List list=new ArrayList<>();
            list.add(new Contact(101,"pvr", "pvr@email.com","gnt"));
            list.add(new Contact(102,"ven","ven@gmail.com","hyd"));
            Map map = convertToMap(list);
            System.out.println(map);

            System.out.println(map.get(101));
            System.out.println(map.get(102));
            }
            }

  11. Iterators allow the caller to remove elements from the underlying collection during the iteration with its remove() method. You can not add/remove elements from a collection when using Iterator.

    Just noticed something in the above statement and would like to clarify, you meant Enumerator in the second statement?

      1. What Ramesh is saying, instead of this line – “You can not add/remove elements from a collection when using Iterator”, it should be “You can not add/remove elements from a collection when using Enumerator”.

        Nice article by the way..keep it up..

      2. Hi Lokesh,

        While using the iterator, it is allowing to remove but not add the elements. As per my understanding , iterator is used for just retrieving the elements only.

        My question is, why iterator allows remove the elements? what was the reason behind that?

  12. Question 24
    ListIterator allows you modify the list using add() remove() methods. Using Iterator you can not do this.

    -using iterator we can remove but can’t add.

    -Manish

  13. Treset allows null only once.
    ex:
    Set s = new TreeSet();
    s.add(null);
    s.add(null); // throws NULL pointer exception

  14. hi lokesh,
    i have probelm actually my boss said to me to create a website in java that is generally like a community block.
    but i dont know how to implement that and which technogies is best just tell me.

    1. Sorry for late reply as I was on vacation in last week.

      I believe its not technology what matters. Today, you can build any website with any set of technologies. The thing which matter, is what you want to build.

      If I have been in your place, I will first understand the requirements (present as well as future). Then write a good and flexible design and get it reviewed with some brilliant mind and experienced colleagues.

      Finally, implement it in any good MVC framework like struts or spring.

      1. I guess he meant, that we can insert null in treeset too if we have 1 or more then one element in tree set. Tree set throw null pointer exception when first element added is null.
        You said that tree set doesn’t allow nulls.

        By the way nice blog. i regularly follow your blog. I am fond of Java and wordpress.
        My blog http://www.examsbook.com/

Note:- In comment box, please put your code inside [java] ... [/java] OR [xml] ... [/xml] tags otherwise it may not appear as intended.

Leave a Reply

Your email address will not be published. Required fields are marked *


8 − six =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>