Java ArrayList and Vector Insights
Java ArrayList and Vector Insights
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 .