These Java Collections interview questions cover the interfaces, implementation choices and iteration rules used in everyday Java code. The right choice depends on the ordering, uniqueness, lookup and concurrency guarantees a task needs.
The answers use small examples to show the behavior behind each choice, including how a collection responds to duplicates, iteration and unsupported operations.
Java Collections Framework Questions
1. What Is the Java Collections Framework?
The framework provides interfaces such as List, Set, and Queue, implementations such as ArrayList and HashSet, and common operations for working with groups of elements. Code can name the interface it needs while choosing an implementation that fits the required ordering, uniqueness, and cost.
List<String> steps = new ArrayList<>();
steps.add("build");
steps.add("test");
System.out.println(steps.get(0)); // build
The caller requests an ordered list with indexed access. It can change the implementation later without changing the operations used by this example. A Map belongs to the wider framework but has its own key-value interface hierarchy.
2. How Are the Main Collection Interfaces Related?

Iterable supplies iteration. Collection adds size, membership, and element operations. List, Set, and Queue extend Collection with different contracts. Map is separate because it associates keys with values.
Iterable
└─ Collection
├─ List ordered positions, duplicates allowed
├─ Set unique elements
└─ Queue elements waiting for processing
Map key → value associations
Order is an implementation or interface guarantee, not a universal property of all sets or queues. For example, a TreeSet sorts elements and a PriorityQueue orders removals by priority.
3. Why Does Collection Not Extend Cloneable or Serializable?
The Collection interface promises element operations, not a universal copy or serialization format. A concrete implementation may support those capabilities, but a caller with only a Collection reference cannot assume them.
Collection<E> reference → add, remove, iterate, size
Specific implementation → may also support cloning or serialization
When the caller needs a copy, choose the semantics explicitly, such as new ArrayList<>(source) for a shallow list copy. This avoids relying on implementation-specific clone() behavior.
4. Why Does Map Not Extend Collection?
A Collection holds individual elements. A Map associates a key with a value, so its core operation is put(key, value) rather than add(element). It remains part of the wider Collections Framework.
Map<String, Integer> stock = Map.of("pen", 4);
Set<String> keys = stock.keySet();
Collection<Integer> values = stock.values();
The map itself is not a Collection, but its key and value views let callers use collection operations where they make sense.
5. What Does a List Guarantee?
A List retains elements in positional order and permits duplicates. ArrayList is a common default for indexed access; LinkedList is a linked implementation with different access and memory costs.
List<String> steps = new ArrayList<>(List.of("build", "test", "build"));
System.out.println(steps.get(0)); // build
System.out.println(steps.size()); // 3
The second build remains in the list. Choose a Set instead when duplicates are not allowed by the task.
6. How Do We Convert an Array to a List?
Arrays.asList() returns a fixed-size view backed by a reference-type array. List.of() creates an unmodifiable list, while an ArrayList copy supports adding and removing elements.
String[] words = {"build", "test"};
List<String> view = Arrays.asList(words);
List<String> mutable = new ArrayList<>(view);
mutable.add("ship");
System.out.println(view); // [build, test]
System.out.println(mutable); // [build, test, ship]
For a primitive array, Arrays.asList(array) produces one element containing the whole array. Box values explicitly if a List
7. How Do We Reverse a List?
Collections.reverse() changes a mutable list in place.
List<String> steps = new ArrayList<>(List.of("build", "test", "ship"));
Collections.reverse(steps);
System.out.println(steps); // [ship, test, build]
An unmodifiable list rejects this operation. Copy it into a mutable list first if the original must stay unchanged.
8. What Does a Set Guarantee?
A Set contains no duplicate elements under its equality rule. Ordering depends on the implementation: HashSet gives no iteration-order guarantee, LinkedHashSet retains insertion order, and TreeSet sorts by its comparator or natural order.
Set<String> tags = new LinkedHashSet<>();
tags.add("java");
tags.add("java");
tags.add("spring");
System.out.println(tags); // [java, spring]
The second java is ignored. Use the interface in an API when callers need uniqueness, and choose the implementation when the order matters.
9. How Does HashSet Keep Elements Unique?
HashSet uses a hash table. A new element’s hashCode() selects a bucket, and equals() distinguishes elements within that bucket. Equal elements cannot be added twice.
record UserId(long value) {}
Set<UserId> users = new HashSet<>();
System.out.println(users.add(new UserId(7))); // true
System.out.println(users.add(new UserId(7))); // false
The record supplies consistent equals() and hashCode() methods. The second add() returns false because the set already contains an equal value.
10. Can We Add null to a HashSet or TreeSet?
HashSet permits one null. A TreeSet using natural ordering cannot compare null with its other elements and rejects it. A custom comparator can define how null sorts, but allowing it must be an explicit choice.
Set<String> hashed = new HashSet<>();
hashed.add(null);
System.out.println(hashed.size()); // 1
Set<String> sorted = new TreeSet<>(Comparator.nullsFirst(String::compareTo));
sorted.add(null);
sorted.add("a");
System.out.println(sorted); // [null, a]
The comparator makes the ordering of null explicit. Without it, natural ordering cannot compare null with strings.
11. What is a Map? What are Core Classes Implementing Map Interface?
- A Map interface is a special type of collection that is used to store key-value pairs.
- Map does not extend Collection interface.
- Map interface provides methods to add, remove, search or iterate over various views of Map.
Common choices are HashMap, LinkedHashMap, TreeMap, EnumMap, and ConcurrentHashMap. Choose by ordering, key type, and concurrency needs.
Map<String, Integer> stock = new HashMap<>();
stock.put("pen", 4);
System.out.println(stock.get("pen")); // 4
A Map associates unique keys with values; it is not itself a Collection.
12. How Do IdentityHashMap and WeakHashMap Differ?
IdentityHashMap compares key references with ==. WeakHashMap uses ordinary key equality but holds keys weakly, so a mapping can disappear when its key is no longer strongly reachable.
Map<Object, String> identities = new IdentityHashMap<>();
Object first = new String("id");
Object second = new String("id");
identities.put(first, "first");
identities.put(second, "second");
System.out.println(identities.size()); // 2
The two strings are equal in value but distinct objects. A WeakHashMap is appropriate only when automatic key reclamation is acceptable; its values are strongly referenced and must not keep their keys alive indirectly.
13. What is ConcurrentHashMap? How Does It Maintain Concurrency?
ConcurrentHashMap is an alternative to HashMap class to be safely used in the concurrent environment.
A ConcurrentHashMap supports concurrent retrievals and updates without locking the entire map.
Read More: ConcurrentHashMap Interview Questions.
ConcurrentMap<String, Integer> counts = new ConcurrentHashMap<>();
counts.merge("done", 1, Integer::sum);
merge() performs the update atomically for a key. A separate get() followed by put() would allow another thread to interleave.
14. How Does HashMap Find a Value?
HashMap uses the key’s hash code to select a bucket. It then compares candidate keys with equals(); an equal key replaces the prior value on put(). Collisions may share a bucket, so a correct key needs a stable hash code and a consistent equality method.
record UserId(long value) {}
Map<UserId, String> names = new HashMap<>();
names.put(new UserId(7), "Ada");
System.out.println(names.get(new UserId(7))); // Ada
The second UserId is a different object but is equal by record value. That is why the lookup succeeds. The HashMap internals guide covers bucket resizing and tree bins.
15. What Makes a Good HashMap Key?
A key must keep the same equality and hash-code behavior while it is in the map. If two keys are equal, they must have equal hash codes. An immutable value object makes that rule easier to maintain.
record UserId(long value) {}
Map<UserId, String> names = new HashMap<>();
names.put(new UserId(7), "Ada");
System.out.println(names.get(new UserId(7))); // Ada
The record generates value-based equals() and hashCode(). If a mutable key changes after insertion, a later lookup may search the wrong bucket and fail to find it.
16. Which Views Does Map Provide?
keySet() returns a Set of keys, values() returns a Collection of values, and entrySet() returns a Set of key-value entries. Values are not necessarily unique, so values() is not a set.
Map<String, Integer> scores = new HashMap<>(Map.of("Ada", 5, "Lin", 5));
Set<String> keys = scores.keySet();
Collection<Integer> values = scores.values();
Set<Map.Entry<String, Integer>> entries = scores.entrySet();
System.out.println(values); // two values, both 5
These views are backed by the map. Removing a key through keys.remove() also removes its mapping, while unsupported additions through a view throw an exception.
17. When Should We Choose HashMap or TreeMap?
Choose HashMap for general key lookup when iteration order does not matter. Choose TreeMap when keys must be sorted or callers need range queries. TreeMap is a separate implementation based on a balanced tree, not a subclass of HashMap.
Map<String, Integer> lookup = new HashMap<>();
NavigableMap<String, Integer> sorted = new TreeMap<>();
sorted.put("a", 1);
sorted.put("c", 3);
System.out.println(sorted.floorKey("b")); // a
The tree uses natural ordering or a supplied Comparator. Its keys must be mutually comparable under that ordering.
18. What Is the Difference Between a Set and a List?
A List keeps positional order and duplicates. A Set keeps unique elements; some implementations also provide insertion or sorted order.
List<String> list = List.of("a", "a");
Set<String> set = Set.copyOf(list);
System.out.println(list.size() + "," + set.size()); // 2,1
Whether null is allowed depends on the implementation, so it is not a general distinction between the two interfaces.
19. What Is the Difference Between a List and a Map?
A List retrieves elements by position; a Map retrieves a value by key. A map is part of the Collections Framework but does not implement Collection.
List<String> labels = List.of("draft", "published");
Map<String, Integer> counts = Map.of("draft", 2, "published", 5);
System.out.println(labels.get(0)); // draft
System.out.println(counts.get("draft")); // 2
Choose a map when the caller knows a key and needs its associated value, rather than relying on a positional index.
23. What Is the Difference Between HashMap and HashSet?
HashMap associates unique keys with values. HashSet stores unique elements. Both use hashing and give no iteration-order guarantee.
Set<String> names = new HashSet<>();
names.add("Ada");
Map<String, Integer> ages = new HashMap<>();
ages.put("Ada", 30);
Use the set for a membership question, and the map when each name needs an age.
24. How Do Iterator and ListIterator Differ?
An Iterator traverses forward and can remove its current element when supported. A ListIterator is specific to lists and can move backward, add an element at its cursor, or replace the last returned element.
List<String> values = new ArrayList<>(List.of("a", "b"));
ListIterator<String> cursor = values.listIterator(values.size());
System.out.println(cursor.previous()); // b
cursor.set("B");
System.out.println(values); // [a, B]
Choose ListIterator when the cursor position and bidirectional edits matter.
25. What Is the Difference Between TreeSet and SortedSet?
SortedSet is an interface for a set whose elements have a defined order. TreeSet is one implementation; it uses natural ordering or a supplied Comparator.
SortedSet<String> names = new TreeSet<>();
names.add("Lin");
names.add("Ada");
System.out.println(names.first()); // Ada
Name the interface when callers need sorting, and choose an implementation according to the storage and operation costs.
26. How Do ArrayList and LinkedList Differ?
ArrayList stores references in a resizable array and offers fast indexed access. LinkedList stores nodes with previous and next links, so indexed access requires traversal. Node insertion after a known list-iterator position can be cheap, but finding that position still costs time.
List<String> indexed = new ArrayList<>(List.of("a", "b"));
System.out.println(indexed.get(1)); // b
Deque<String> queue = new ArrayDeque<>();
queue.addLast("task");
Start with ArrayList for general lists. If the real requirement is a queue or stack, ArrayDeque states that intent more directly than choosing LinkedList for its nodes.
27. How Do We Create an Unmodifiable Collection?
Use List.copyOf() for an unmodifiable snapshot, or Collections.unmodifiableList() for an unmodifiable view of an existing list. The view reflects later changes made through the backing list.
List<String> mutable = new ArrayList<>(List.of("Ada"));
List<String> snapshot = List.copyOf(mutable);
List<String> view = Collections.unmodifiableList(mutable);
mutable.add("Lin");
System.out.println(snapshot); // [Ada]
System.out.println(view); // [Ada, Lin]
Both reject mutation through their own references, but only the snapshot stays unchanged when the backing list changes.
28. How Do We Make Collection Access Thread-Safe?
Collections.synchronizedList() wraps each operation with synchronization. For compound actions such as iteration, lock the returned wrapper for the whole action. Concurrent collections offer different guarantees and may fit a workload better.
List<String> safe = Collections.synchronizedList(new ArrayList<>());
safe.add("Ada");
synchronized (safe) {
for (String name : safe) System.out.println(name);
}
The lock covers the entire traversal, so another caller using the wrapper cannot modify it mid-iteration. A synchronized wrapper does not automatically make arbitrary sequences of separate calls atomic.
29. Why Doesn’t Iterator Have add()?
An ordinary Iterator has no general insertion position. A list’s cursor has one, so ListIterator adds add() to its contract.
List<String> steps = new ArrayList<>(List.of("test"));
ListIterator<String> cursor = steps.listIterator();
cursor.add("build");
System.out.println(steps); // [build, test]
The ability to add an element to a collection does not imply that insertion during an arbitrary traversal has a clear meaning.
30. How Can We Iterate a List?
A for-each loop is clear for reading each element. An indexed loop is useful when positions matter; an Iterator is useful when removing the current element.
List<String> names = List.of("Ada", "Lin");
for (String name : names) System.out.println(name);
for (int i = 0; i < names.size(); i++) System.out.println(i + ": " + names.get(i));
The first loop prints values, and the second also prints their positions. Choose by the operation the loop needs.
31. What Does a Fail-Fast Iterator Do?
An ArrayList iterator commonly checks whether the list was structurally changed outside that iterator after it was created. It may throw ConcurrentModificationException when it detects a change. The check is best effort, not a thread-safety guarantee.
List<String> names = new ArrayList<>(List.of("Ada"));
Iterator<String> cursor = names.iterator();
names.add("Lin");
cursor.next(); // normally throws ConcurrentModificationException
Use the iterator’s own remove() for supported removal during traversal.
32. How Do Fail-Fast, Snapshot, and Weakly Consistent Iterators Differ?
An ArrayList iterator may detect structural changes and fail. A CopyOnWriteArrayList iterator sees a snapshot from creation time. A ConcurrentHashMap iterator is weakly consistent: it can reflect some concurrent changes without throwing ConcurrentModificationException.
CopyOnWriteArrayList<String> names = new CopyOnWriteArrayList<>(List.of("Ada"));
Iterator<String> snapshot = names.iterator();
names.add("Lin");
System.out.println(snapshot.next()); // Ada
System.out.println(snapshot.hasNext()); // false
“Fail-safe” is an informal label that hides the difference between snapshot and weakly consistent iteration.
33. How Do We Avoid ConcurrentModificationException During Iteration?
Use the iterator’s own remove() method when deleting the current element. For bulk filtering, removeIf() can be clearer. Do not change an ArrayList directly while traversing it with a fail-fast iterator.
List<String> names = new ArrayList<>(List.of("Ada", "", "Lin"));
Iterator<String> it = names.iterator();
while (it.hasNext()) {
if (it.next().isBlank()) it.remove();
}
System.out.println(names); // [Ada, Lin]
When multiple threads modify the data, choose a synchronization or concurrent-collection strategy based on the required iteration consistency. Avoiding this exception alone does not make access thread-safe.
34. When Does a Collection Throw UnsupportedOperationException?
A collection operation may be optional under an interface’s contract. The implementation throws UnsupportedOperationException when it does not support that operation.
List<String> fixed = Arrays.asList("a", "b");
fixed.set(0, "c"); // supported replacement
fixed.add("d"); // throws UnsupportedOperationException
Arrays.asList() returns a fixed-size list backed by the array, so replacement works but changing its size does not. An unmodifiable list rejects replacement as well.
35. Which Lists Provide Fast Indexed Access?
RandomAccess is a marker interface used by lists with fast indexed access, such as ArrayList. It does not describe map lookup by key.
List<String> values = new ArrayList<>(List.of("a", "b"));
System.out.println(values instanceof RandomAccess); // true
System.out.println(values.get(1)); // b
LinkedList does not implement RandomAccess because an indexed lookup walks nodes. The marker is a useful hint for algorithms choosing between indexed and iterator traversal.
36. What Does a BlockingQueue Add to Queue?
A BlockingQueue can wait for an element with take() or for capacity with put(). Other methods return a status, throw, or wait with a timeout, so the caller can choose the needed back-pressure behavior.
BlockingQueue<String> jobs = new ArrayBlockingQueue<>(2);
jobs.put("job-1");
System.out.println(jobs.take()); // job-1
The two operations coordinate a producer and consumer. Handle interruption when using blocking operations in a real worker.
37. How Do Queue and Stack Behavior Differ?
A FIFO queue removes the oldest waiting item. A LIFO stack removes the most recently added item. Deque provides operations for both; a PriorityQueue instead removes according to priority, so not every queue is FIFO.
Deque<String> work = new ArrayDeque<>();
work.addLast("first");
work.addLast("second");
System.out.println(work.removeFirst()); // FIFO: first
work.push("urgent");
System.out.println(work.pop()); // LIFO: urgent
Choose operation names that reveal the intended order to the next reader.
38. How Do Comparable and Comparator Differ?
Comparable defines a type’s natural order. A Comparator supplies an order for a particular use, including types that have no natural order.
record Item(String name, int price) {}
List<Item> items = List.of(new Item("pen", 3), new Item("book", 7));
Comparator<Item> byPrice = Comparator.comparingInt(Item::price);
List<Item> sorted = items.stream().sorted(byPrice).toList();
System.out.println(sorted.get(0).name()); // pen
The record does not implement Comparable, but the comparator still sorts it by price. A TreeSet or TreeMap can also receive a comparator at construction.
39. How Do Collections and Arrays Differ?
Collections contains algorithms and wrappers for collection objects. Arrays contains operations for Java arrays, including sorting and conversion to a list view.
List<String> names = new ArrayList<>(List.of("b", "a"));
Collections.sort(names);
String[] array = {"b", "a"};
Arrays.sort(array);
System.out.println(names); // [a, b]
System.out.println(Arrays.toString(array)); // [a, b]
Both sort calls mutate their input. When the input must stay unchanged, copy it before sorting.
Further Reading
Read the following posts to understand the Collections framework in-depth.
Happy Learning!
Hi,
In Q 33 you said Use ListIterator to avoid ConcurrentModificationException
But ListListIterator is also fail-fast
Please refer to Java docs
I used Collections.unmodifiableList(list); and tried to add or remove an element from the list. But it didn’t throw me
UnsupportedOperationException.
List list = new ArrayList() ;
Collections.unmodifiableList(list) returns a list. You are ignoring the result.
Try:
List list = Collections.unmodifiableList(new ArrayList());
you are shareing useful information for me
Excellent commentary – I Appreciate the insight . Does someone know if my company could get a fillable IRS 943 copy to work with ?
Hi,
Please chk Q.35, Random Access is only implemented by ArrayList and Vector in whole collection framework….but u mentioned
HashMap, TreeMap, Hashtable . please chk and update…
Thanks
Laltu
I believe you understood the question incorrectly. It’s not about
RandomAccessinterface.Difference between ArrayList and LinkedList?
Just to add few things here
On a LinkedList
Finding the point of insertion/deletion is O(n) but Performing the insertion/deletion is O(1)
On a ArrayList its reverse i.e.
Finding the point of insertion/deletion is O(1) but Performing the insertion/deletion is O(n)
What are different Collection views provided by Map interface?
why is it called “value set view”, It should be “values” as they can be duplicate on the map it cannot be “value set”
Good observation :-) I will try to research on it.
Map deals with key-value pairs – Values may be duplicate but key for each value must be unique i.e why
Thanks. I haven’t seen such a pretty good explained blog on collections. Just Awesome.
Awesome article. Read your post about how HashMap works for too good .
Thanks. Much appreciated.
thanks for awsm article. looking forward for more interesting topics
We can add null as a key to HashMap.
Question is how to retrieve assigned object to this key?
@Shisher : In case of hashmap only one null key is allowed and that null key is always stored at zero index.
Hi Lokesh,
This is Krishna.
It is very nice to interact with you.
I have a doubt on very basics. You may think it’s silly.
But i’m confusing a little at that.
The point is ArrayList class is inheriting the properties of both List interfase and AbstractList
(As per api
public class ArrayList
extends AbstractList
implements List).
Why both?
I think, Inheriting AbstractList is sufficient.
I have gone through your Interfaces and Abstract Classes article. but i didn’t get it.
Thanks & Regards,
Krishna.
Hi Krishna,
Nice Observation!!
ArrayList could have done with either implmenting List or extending AbstractList but that would have prevented polmorphism.
for eg: List list = new ArrayList();
AbstractList list = new ArrayList();
This would not have been possible otherwise.
Thnx
AbstractList is already implementing List interface. I dont think it is needed.
Nice Observation, I feel by explicitly implementing the List interface ArrayList announces that it is an implementation of List. In case this was not done then it would have been a simple abstraction to the AbstractList and then an extra code dig in would have been needed to know that ArrayList is an implementation of the List interface. Moreover I feel ArrayList provides its own implementation of all the methods declared in the List interface and do not uses the List methods implemented by parent class AbstractList.
Collection classes contain interface abstract classes and concrete classes so List is a interface extending from AbstractList and it have implementation some more concrete classes like Arraylist linklist vector stack …..
So abstract classes are fully unimplemented classes we can’t use it that’s why they they are given concrete classes
Hope you understand..
public class TreeSet extends AbstractSet
implements NavigableSet, Cloneable, java.io.Serializable
Very nice article… Very much useful Q’s & A’s…
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
Run below simple program:
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.
upto java6 we were able to insert one null value but java7 onwards we can not insert any null value.
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
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
Thanks for the suggestion. I will cover it in separate post.
Hi Lokesh,
Can you send me the latest interview question related to String/String Buffer.
Thanks, it helps me a lot.
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
you are absolutely right. I will update the post.
nice Lokesh..keep it up….really helpful blog….
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){
}
}
}
Thanks for sharing.
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?
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.
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
You answered the question correctly. Either you didn’t explain it well or interviewer has already any specific answer in his mind and it wanted you to read his mind. Nobody can satisfy the interviewer in second case. Leave it considering a bad day for you.
More discussion can be found here: https://stackoverflow.com/questions/18799591/print-natural-sequence-with-help-of-2-threads1-is-printing-even-and-2nd-is-pri
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
A good solution can be using Semaphore. Read more about Semaphore here: https://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 { list1 = Arrays.asList(new Integer[]{1,2,3,4,5}); list2 = Arrays.asList(new Integer[]{1,2,3,4,5}); list3 = Arrays.asList(new Integer[]{1,2,3,4,5});
private List
private List
private List
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
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???
Hi Surjeet,
Thanks for sharing your interview experience.:)
Hi Surjeet, Could you please share the full code in both the approaches like using wait() and notify() methods and also using Semaphore.
You could have mentioned the usage of boolean to tell which thread’s turn to wait and notify
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.
OOPS !! It is typo mistake. Corrected it.
Hi Lokesh..
good work.. Thanks
Great Work Lokesh :)
Keep it up!
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)
I believe Yes.
Good collection of Collection!!!! :-)
:)
Hi Lokesh, i hv one doubt, why Hashmap allows null key, whats the main purpose and its benefit
Hi Lokesh,
How I can get the bucket location with highest number of Map.Entry objects?
Thanks in Advance.
I think HashMap does not provide any such way. But, you can extend the HashMap and override relevant methods and maintain counters for added entries.
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.
You need to extend HashMap class and add modified behavior.
Excellent collection on Collection(s).
Keep it up ! :-)
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
You have remove() method. What’s problem in this?
Hi Lokesh,
Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection?
Explain me with an example
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
I would like to encourage you to write this program. Let me know (with code) what stops you.
I can’t understand this code,i have no idea,please help me,
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);
}
}
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 = new HashMap();
Map
for (Contact c : list) {
map.put(c.getId(), c);
}
return map;
}
public static void main(String[] args){ list=new ArrayList<>(); map = convertToMap(list);
List
list.add(new Contact(101,"pvr", "pvr@email.com","gnt"));
list.add(new Contact(102,"ven","ven@gmail.com","hyd"));
Map
System.out.println(map);
System.out.println(map.get(101));
System.out.println(map.get(102));
}
}
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?
Ramesh, Can you please be more specific about context? Not sure where you are pointing to with “second statement”?
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..
OK, but it’s already had been corrected. Ramesh and Debarshi, Thanks for clearing up.
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?
iterators ae meant to iterate, thats why once the collection is modified mid iteration, iterator throws exception.
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
Fair enough. I will make the update.
Question 23.- has Hashset as ordered but they are unordered.
Treset allows null only once.
ex:
Set s = new TreeSet();
s.add(null);
s.add(null); // throws NULL pointer exception
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.
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.
TreeSet Wont support null as value.
Hi. Spotted a minor error in question 7 about the Collections.reverse method. That method mutates the argument list, and does not return any value, so your example won’t compile.
TreeSet supports null. But a single entry should be there for multiple only it will throw NPE
Hey sunny, thanks for comment. But I am really unable to gt what you are pointing to.
Can you please give any code sample, which will make things more clear??
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 https://www.examsbook.com/
Hey Shankar, your site also looks good buddy. good going.
I more into Java. this is just hobby work.. :)