Consider the following code:
import java.util.PriorityQueue;
public class Test {
public static void main(String argv[]) {
PriorityQueue<A> queue = new PriorityQueue<>();
System.out.println("Size of queue is " + queue.size()); // prints 0
try {
queue.add(new A());
} catch (ClassCastException ignored) { }
System.out.println("Size of queue is " + queue.size()); // prints 1
}
}
class A { } // non-comparable object
In this code, an object, which is explicitly non-comparable, is added to a PriorityQueue
. As expected per PriorityQueue.add
Javadoc, this code throws a ClassCastException
because the object is not comparable.
However, it seems that the size of the queue is still increased, although an exception was thrown.
I would have expected both print statements to output 0 but the second one actually outputs 1, as if an object had been added to the queue.
I find this really strange, is this behaviour expected? If so, what is the reason behind this and where is it documented? I can't find anything related to this.
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire