I'm having hard time digesting this particular code block from java.util.PriorityQueue#initElementsFromCollection method.
/**
* Initializes queue array with elements from the given Collection.
*
* @param c the collection
*/
private void initFromCollection(Collection<? extends E> c) {
initElementsFromCollection(c);
heapify();
}
private void initElementsFromCollection(Collection<? extends E> c) {
Object[] es = c.toArray();
int len = es.length;
if (c.getClass() != ArrayList.class)
es = Arrays.copyOf(es, len, Object[].class);
if (len == 1 || this.comparator != null)
for (Object e : es)
if (e == null)
throw new NullPointerException();
this.queue = ensureNonEmpty(es);
this.size = len;
}
I can understand that the code here tries to build the Heap from the collection elements supplied via constructor but why are they checking the class type of Collection argument against ArrayList and again copying the elements, it has already been copied into Object[] es using toArray?
if (c.getClass() != ArrayList.class)
es = Arrays.copyOf(es, len, Object[].class);
Is anything magical happening in java.util.Arrays#copyOf(U[], int, java.lang.Class<? extends T[]>) ?
java-11