TreeSet HashSet

很多文章都记录了TreeSet、和HashSet的各种比较,但是很少有人去指出什么情况下应该使用TreeSet

以下摘自http://stackoverflow.com/questions/1463284/hashset-vs-treeset#comment14600884_4464394

感觉里面有几个回答比较好,特此记录以下:

One advantage not yet mentioned of a TreeSet is that its has greater "locality", which is shorthand for saying (1) if two entries are nearby in the order, a TreeSet places them near each other in the data structure, and hence in memory; and (2) this placement takes advantage of the principle of locality, which says that similar data is often accessed by an application with similar frequency.

This is in contrast to a HashSet, which spreads the entries all over memory, no matter what their keys are.

When the latency cost of reading from a hard drive is thousands of times the cost of reading from cache or RAM, and when the data really is accessed with locality, the TreeSet can be a much better choice.

原文地址:https://www.cnblogs.com/kakaxisir/p/4437557.html