TreeSet真正的强大和优势在于它实现的接口——NavigableSet
为什么它如此强大,在什么情况下?
Navigable Set 接口添加例如这 3 个不错的方法:
headSet(E toElement, boolean inclusive)
tailSet(E fromElement, boolean inclusive)
subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive)
这些方法允许组织有效的搜索算法(非常快)。
示例:我们需要找到所有以 Milla 开头并以 Wladimir 结尾的名字:
TreeSet<String> authors = new TreeSet<String>();
authors.add("Andreas Gryphius");
authors.add("Fjodor Michailowitsch Dostojewski");
authors.add("Alexander Puschkin");
authors.add("Ruslana Lyzhichko");
authors.add("Wladimir Klitschko");
authors.add("Andrij Schewtschenko");
authors.add("Wayne Gretzky");
authors.add("Johann Jakob Christoffel");
authors.add("Milla Jovovich");
authors.add("Taras Schewtschenko");
System.out.println(authors.subSet("Milla", "Wladimir"));
输出:
[Milla Jovovich, Ruslana Lyzhichko, Taras Schewtschenko, Wayne Gretzky]
TreeSet 不会遍历所有元素,它会查找第一个和最后一个元素并返回一个包含范围内所有元素的新集合。