Tricky Java ArrayList and Vector Concepts
Tricky Java ArrayList / Vector Questions
Q1. What will be the output of this?
ArrayList<String> list = new ArrayList<>(5);
list.add("A");
list.add("B");
list.add("C");
list.ensureCapacity(1000);
System.out.println(list.size());
Answer: 3
Q2. What happens here?
ArrayList<String> list = new ArrayList<>();
list.add(null);
list.add("Java");
System.out.println(list.get(0).length());
Throws: NullPointerException
Q3. Spot the issue:
Vector<Integer> v = new Vector<>();
v.add(1);
v.add(2);
v.remove(1);
Answer: 2 is removed
Q4. Will this compile?
ArrayList<int[]> list = new ArrayList<>();
list.add(new int[]{1,2,3});
System.out.println(list.get(0)[1]);
Answer: Yes, and output will be 2.
Q5. Infinite Growth?
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < Integer.MAX_VALUE; i++) {
list.add(i);
Answer: Throws OutOfMemoryError
Q6. What's the difference?
List<Integer> list = new ArrayList<>();
list.add(10);
list.add(20);
for (int i = 0; i < list.size(); i++) {
list.remove(i);
System.out.println(list);
Output: [20]
Q7. What does this return?
ArrayList<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
System.out.println(list.indexOf("D"));
Answer: -1
Q8. Which is faster: ArrayList.remove(index) or Vector.remove(index)?
Answer: ArrayList is usually faster (if single-threaded)
Q9. Is this safe?
ArrayList<String> list = new ArrayList<>();
list.add("A");
list.add("B");
for (String s : list) {
list.remove(s);
Throws: ConcurrentModificationException
Q10. Will this compile and work?
List list = new ArrayList();
list.add("Java");
list.add(123);
System.out.println(list);
Answer: Yes. Output: [Java, 123]
Tricky Concepts + Puzzles (Advanced-Level Java)
Q11. Fail-Fast vs Fail-Safe
ArrayList will throw ConcurrentModificationException.
CopyOnWriteArrayList won't.
Q12. Removing in Loops
Output: [2, 4]
Q13. Unsafe Multi-threading
Using ArrayList with threads can cause data corruption.
Q14. Immutable Arrays.asList Trap
Arrays.asList().add() => UnsupportedOperationException
Q15. Auto-unboxing Trap
list.get(0) == list.get(1) => false due to Integer caching
Q16. SubList Frozen List Trap
subList.clear() also affects the original list.
Q17. Cloning Deep Trap
Shallow copy, both point to same inner list.
Q18. Capacity vs Size Confusion
size() returns 0 even if capacity is 100.
Q19. ArrayList + equals()
l1.equals(l2) => true (checks values, not reference)
Q20. Synchronized Block on ArrayList
Need synchronized block while iterating a synchronizedList.