What are the defining properties of an ArrayList?
ArrayList is an ordered, resizable collection of object references. Its size and elements can change, and duplicate values are allowed.
Study Java ArrayList Algorithms and Collections with 12 free online flashcards. Review key terms, definitions, and concepts with this interactive flashcard deck.
What are the defining properties of an ArrayList?
ArrayList is an ordered, resizable collection of object references. Its size and elements can change, and duplicate values are allowed.
How do add(index, value) and set(index, value) differ?
add(index, value) inserts and increases the size, shifting later elements right. set(index, value) replaces an existing element without changing the size.
What indexes are valid for ArrayList access and insertion?
For access or replacement, valid indexes are 0 through size() - 1. An index equal to size() is valid only for insertion with add(index, value).
What does remove(1) mean for an ArrayList<Integer>?
In an ArrayList<Integer>, remove(1) removes the element at index 1. To remove the value 1, use remove(Integer.valueOf(1)).
Why is i < list.size() usually correct in an index loop?
Use i < list.size(). With i <= list.size(), the loop eventually attempts to access index size(), which is outside the valid range.
When should you choose an enhanced for loop?
Use an enhanced for loop when each element is needed but its index is not. Use an index-based loop when the index or controlled modification is required.
Why does backward traversal safely remove matching elements?
Traverse from the last index down to zero. Removing an element only shifts elements to its right, which have already been processed in a backward traversal.
How can a while loop remove elements without skipping any?
After removing at index i, do not increment i; examine the new element now at i. Increment i only when no removal occurs.
Why can’t an ArrayList use int as its type parameter?
Use wrapper types such as Integer, Double, or Boolean because ArrayList stores objects, not primitive values. For example, use ArrayList<Integer>, not ArrayList<int>.
What are autoboxing and unboxing?
Autoboxing converts a primitive to its wrapper object, while unboxing converts a wrapper object to its primitive value. Unboxing a null wrapper causes NullPointerException.
How should a maximum algorithm initialize its candidate?
Initialize the maximum from the first element, such as numbers.get(0), rather than from 0. Starting at 0 fails when all values are negative.
Why does duplicate detection compare j from i + 1?
Start the inner loop at i + 1. This avoids comparing an element with itself and checks each unordered pair only once.