Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing "Queue" objects in Java

I'm currently studying the properties of "Queue" interface and have encountered the following statement in Java Documentation:

Queue implementations generally do not define element-based versions of methods equals and hashCode but instead inherit the identity based versions from class Object, because element-based equality is not always well-defined for queues with the same elements but different ordering properties.

I'm not exactly sure the meaning of this paragraph in terms of how to compare "Queue" objects of both the same implementation type and different implementation type. Could someone please explain to me how comparing "Queue" objects is done?

like image 286
Thor Avatar asked Mar 09 '23 20:03

Thor


1 Answers

I think the documentation is stating that Queue implementations do not generally override the default equals method from the Object class as the ordering of elements within a Queue can greatly differ for each implementation and thus comparing them in a generic way may give unexpected results.

If you want to compare Queue objects based on your own criteria you can implement a Comparator<Queue> class (specifically the compare method). You can then use this method to directly compare two Queues, or use it to sort a collection of Queues etc.

See the javadoc for Comparator

like image 123
jwaddell Avatar answered Mar 21 '23 08:03

jwaddell