Entrance Exams
Govt. Exams
Fail-fast iterators throw ConcurrentModificationException when collection is modified during iteration.
HashSet uses hash table internally. Average case is O(1), worst case O(n) when hash collisions occur.
collection.stream() returns a sequential stream, while parallelStream() returns a parallel stream.
List list = Arrays.asList("A", "B", "C");
list.add("D");
System.out.println(list.size());
Arrays.asList() returns a fixed-size list backed by array. add() operation is not supported.
TreeMap implements NavigableMap which provides methods like higherKey(), lowerKey(), floorEntry(), etc.
Collection col = new ArrayList();
col.add("Java");
Iterator it = col.iterator();
while(it.hasNext()) {
String s = it.next();
col.remove(s);
}
Modifying collection directly while iterating throws ConcurrentModificationException. Use iterator.remove() instead.
PriorityQueue pq = new PriorityQueue();
pq.add(5);
pq.add(3);
pq.add(7);
System.out.println(pq.peek());
PriorityQueue orders elements based on their natural ordering (min-heap by default). peek() returns 3, the minimum element.
offer() returns false if element cannot be added, while add() throws exception. poll() returns null if empty.
LinkedHashMap map = new LinkedHashMap();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
for(String key : map.keySet()) System.out.print(key);
LinkedHashMap maintains insertion order. Elements are iterated in the order they were inserted.
The add() method in Set returns boolean - true if element is added, false if duplicate exists.