Somewhere in this constructor of PriorityBlockingQueue is hard to understand

Liu via Concurrency-interest <[email protected]> Tue, 4 Aug 2020 20:10:23 +0800 (GMT+08:00)
Newsgroups gmane.comp.java.jsr.166-concurrency
Message-ID <[email protected]>
In this constructor of PriorityBlockingQueue, some codes are hard to understand.


    public PriorityBlockingQueue(Collection<? extends E> c) {
        this.lock = new ReentrantLock();
        this.notEmpty = lock.newCondition();
        boolean heapify = true; // true if not known to be in heap order
        boolean screen = true;  // true if must screen for nulls
        if (c instanceof SortedSet<?>) {
            SortedSet<? extends E> ss = (SortedSet<? extends E>) c;
            this.comparator = (Comparator<? super E>) ss.comparator();
            heapify = false;
        }
        else if (c instanceof PriorityBlockingQueue<?>) {
            PriorityBlockingQueue<? extends E> pq =
                (PriorityBlockingQueue<? extends E>) c;
            this.comparator = (Comparator<? super E>) pq.comparator();
            screen = false;
            if (pq.getClass() == PriorityBlockingQueue.class) // first one
                heapify = false;
        }
        Object[] a = c.toArray();
        int n = a.length;
       
        if (a.getClass() != Object[].class)  // second one
            a = Arrays.copyOf(a, n, Object[].class);
        if (screen && (n == 1 || this.comparator != null)) {  //third one
            for (int i = 0; i < n; ++i)
                if (a[i] == null)
                    throw new NullPointerException();
        }
        this.queue = a;
        this.size = n;
        if (heapify)
            heapify();
    }


1. When "pq.getClass() == PriorityBlockingQueue.class" Expression holds, 
    Then heapify operation is not need to do. Isn't "c instanceof PriorityBlockingQueue<?>" 
    enough to decide?


2. Why must make the actual type of array is Object[].class?


3. I just don't understand  this "&& (n == 1 || this.comparator != null)". Why is it written like this?


In newest JDK, http://hg.openjdk.java.net/jdk/jdk15/file/d2c6eb3b2c8d/src/java.base/share/classes/java/util/concurrent/PriorityBlockingQueue.java#l242 ,
this constructor of PriorityBlockingQueue is same.






--------------------------------------------------------------------------------
Regards
Liu

_______________________________________________
Concurrency-interest mailing list
[email protected]
http://cs.oswego.edu/mailman/listinfo/concurrency-interest