On Mon, 3 Nov 2025 20:45:44 GMT, jengebr <[email protected]> wrote:

> Why use exact class check instead of instanceof for ArrayList?

You might add that in general it might not be correct (or even safe) to do 
these sorts of optimizations on an arbitrary subclass of `ArrayList`. It's 
possible to create a subclass where a snapshot of `elementData` and `size` 
would disagree with the data returned by `toArray`, for example.

src/java.base/share/classes/java/util/ArrayList.java line 753:

> 751:      */
> 752:     public boolean addAll(Collection<? extends E> c) {
> 753:         if (c.getClass() == ArrayList.class) {

Consider simplifying this to reduce code duplication:

Object[] a;
int newNum;
if (c.getClass() == ArrayList.class) {
    ArrayList<?> src = (ArrayList<?>) c;
    a = src.elementData;
    numNew = src.size;
} else {
    a = c.toArray();
    numNew = a.length;
}
modCount++;
...

-------------

Changes requested by redestad (Reviewer).

PR Review: https://git.openjdk.org/jdk/pull/28116#pullrequestreview-3413058471
PR Review Comment: https://git.openjdk.org/jdk/pull/28116#discussion_r2487950683

Reply via email to