my dog learned polymorphism
The moose likes Performance and the fly likes TreeSet that uses the same Comparator? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Performance
Bookmark "TreeSet that uses the same Comparator?" Watch "TreeSet that uses the same Comparator?" New topic

TreeSet that uses the same Comparator?

Jon Camilleri
Ranch Hand

Joined: Apr 25, 2008
Posts: 662

"The API documentation explains that you need
not override the equals method but that doing so may yield improved performance in some
cases. For example, the addAll method of the TreeSet class can work more effectively if you
add elements from another set that uses the same comparator."

Core Java Vol.I (8th Edition) P.674.

Can you clarify and provide an example?

Stephan van Hulst

Joined: Sep 20, 2010
Posts: 4094

If two trees use the same ordering of their elements, adding all of the elements from one tree to another can be made a lot simpler, because a lot of the elements may already be in the correct order, and the tree only has to see which chunks of elements go where.

How can the set tell that another set uses the same ordering? If the comparator it uses equals the comparator of the other set.

The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
I agree. Here's the link:
subject: TreeSet that uses the same Comparator?
jQuery in Action, 3rd edition