I'm trying to port the PriorityQueue class from the OpenJDK implementation to another language (Xojo) that doesn't have a similar data structure. I'm really struggling to break down the following method into pseudocode so I can translate it to Xojo:
public E poll() {
final Object[] es;
final E result;
if ((result = (E) ((es = queue)[0])) != null) {
modCount++;
final int n;
final E x = (E) es[(n = --size)];
es[n] = null;
if (n > 0) {
final Comparator<? super E> cmp;
if ((cmp = comparator) == null)
siftDownComparable(0, x, es, n);
else
siftDownUsingComparator(0, x, es, n, cmp);
}
}
return result;
}
The variable queue is an Object[] array defined on the class.
There are a couple of lines that are confusing me. Firstly:
if ((result = (E) ((es = queue)[0])) != null)
Does this mean "assign the array queue to the variable es and access element 0 and do the following if it's not null?" What does the result = (E) expression mean? I know E is a generic type.
What is the order of operation of final E x = (E) es[(n = --size)];? Does this mean decrement size, assign that value to n and then access this index within the es array? If so, what does x = (E) before this expression mean? I'm guessing it means to cast the element to type E?
Lastly, these lines:
final Comparator<? super E> cmp;
if ((cmp = comparator) == null)
comparator is a class variable (holding a Comparator). Why assign it to a local variable cmp and what does the question mark mean on the first line?
Yes.
Yes.
At the same time as the two expressions above, it also assigns
queue[0]toresult. The(E)is a cast to a type. So it's basically just:With some extra stuff thrown in.
Yes.
Yes, again just a cast like before.
Just to be pedantic,
comparatoris likely an instance variable, not a class variable. Check its definition.I suppose to make a local variable copy. I don't see a good reason to do that in the code, so it might be a mistake or something that was left in after some previous code got changed.
The question mark means the type of the
Comparatoris unknown, and can be anything as long as it's a super class ofE. For example, ifIntegerdoesn't have aComparatorbutNumberdoes, then that's OK,Numberis a super class ofIntegerand that's good enough.