0% found this document useful (0 votes)
7 views4 pages

Java ArrayList and Vector Insights

The document presents a series of tricky questions and answers related to Java's ArrayList and Vector, covering concepts such as capacity, null handling, and thread safety. It highlights common pitfalls like NullPointerExceptions, ConcurrentModificationExceptions, and the differences in behavior between ArrayList and Vector. Additionally, it addresses advanced topics like fail-fast vs fail-safe mechanisms and the implications of using collections in multi-threaded environments.

Uploaded by

noneedd78
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views4 pages

Java ArrayList and Vector Insights

The document presents a series of tricky questions and answers related to Java's ArrayList and Vector, covering concepts such as capacity, null handling, and thread safety. It highlights common pitfalls like NullPointerExceptions, ConcurrentModificationExceptions, and the differences in behavior between ArrayList and Vector. Additionally, it addresses advanced topics like fail-fast vs fail-safe mechanisms and the implications of using collections in multi-threaded environments.

Uploaded by

noneedd78
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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);

[Link]("A");

[Link]("B");

[Link]("C");

[Link](1000);

[Link]([Link]());

Answer: 3

Q2. What happens here?

ArrayList<String> list = new ArrayList<>();

[Link](null);

[Link]("Java");

[Link]([Link](0).length());

Throws: NullPointerException

Q3. Spot the issue:

Vector<Integer> v = new Vector<>();

[Link](1);

[Link](2);

[Link](1);

Answer: 2 is removed
Q4. Will this compile?

ArrayList<int[]> list = new ArrayList<>();

[Link](new int[]{1,2,3});

[Link]([Link](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++) {

[Link](i);

Answer: Throws OutOfMemoryError

Q6. What's the difference?

List<Integer> list = new ArrayList<>();

[Link](10);

[Link](20);

for (int i = 0; i < [Link](); i++) {

[Link](i);

[Link](list);

Output: [20]

Q7. What does this return?

ArrayList<String> list = new ArrayList<>([Link]("A", "B", "C"));

[Link]([Link]("D"));
Answer: -1

Q8. Which is faster: [Link](index) or [Link](index)?

Answer: ArrayList is usually faster (if single-threaded)

Q9. Is this safe?

ArrayList<String> list = new ArrayList<>();

[Link]("A");

[Link]("B");

for (String s : list) {

[Link](s);

Throws: ConcurrentModificationException

Q10. Will this compile and work?

List list = new ArrayList();

[Link]("Java");

[Link](123);

[Link](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 [Link] Trap

[Link]().add() => UnsupportedOperationException

Q15. Auto-unboxing Trap

[Link](0) == [Link](1) => false due to Integer caching

Q16. SubList Frozen List Trap

[Link]() 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()

[Link](l2) => true (checks values, not reference)

Q20. Synchronized Block on ArrayList

Need synchronized block while iterating a synchronizedList.

Common questions

Powered by AI

Java allows null values to be added to an ArrayList, but attempting to call methods on these null entries will cause a NullPointerException, as seen when list.get(0).length() is attempted; since the first element is null, the call to length() fails .

Due to autoboxing, primitive type operations in ArrayLists can lead to subtle logic errors. The expression list.get(0) == list.get(1) compares object references, not values. Java caches Integer objects for small values, but differing references for comparable values cause such expressions to return false unexpectedly if elements are not explicitly uncached integers .

In this Vector example, calling remove(1) removes the element at index 1, which is the element "2". This shows Vector's behavior that remove operates based on index rather than the element value .

CopyOnWriteArrayList offers iteration safety by making a fresh copy of the list with each modification, thus iterations (which access these copies) do not encounter ConcurrentModificationExceptions even in concurrent environments unlike a regular ArrayList .

Attempting to continuously add elements to an ArrayList until it reaches memory limits inevitably results in an OutOfMemoryError. Java dynamically grows the ArrayList capacity, consuming heap memory rapidly until exceeding available resources, thus halting execution .

The ArrayList can accept both strings and integers when declared as List without a type parameter due to Java's type erasure, which removes generic types in runtime. This undermines type safety since different types can coexist in the list, potentially leading to ClassCastException if type-specific operations are performed without caution .

The enhanced for-loop internally uses an iterator to traverse the list, and removing elements directly from the list without using the iterator's remove() method violates the iteration process integrity, leading to ConcurrentModificationException due to structural modification detection during iteration .

The ensureCapacity method in ArrayList pre-allocates memory for future elements to improve performance by reducing reallocations. However, it doesn't affect the functionality or apparent size of the ArrayList, which is why the output of the size() method remains "3", despite setting capacity to 1000 .

The iteration modification leads to unexpected behavior because the list is being modified while iterating, causing elements to shift left each time an element is removed. In this example, only the second element "20" remains because removing the first element collapses the list size, skipping subsequent checks .

Performing operations on a sublist, such as clear(), directly affects the original list because the sublist is backed by the original list. Thus, clearing a sublist will remove those elements from the original list as well, demonstrating a high cohesion between both .

You might also like