欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Set和SortedSet

程序员文章站 2022-05-19 10:11:49
...

The asterisk on HashSet indicates that, in the absence of other constraints, this should be your default choice because it is optimized for speed.
Set和SortedSet
Set和SortedSet
对hashCode( )的定义在后面
对hashed & tree必须写 equals( )方法
但是hashCode( )只有在使用HashSet/LinkedHashSet的时候才需要 (HashSet经常被用到since that should generally be your first choice as a Set implementation)
//However, for good programming style, you should always override hashCode( ) when you override equals( ).

Set和SortedSet

sorted set

因为其中的元素是排好序的,所以会有一些额外的功能
Comparator comparator( ): Produces the Comparator used for this Set, or null for natural ordering.
Object first( ): 最小值
Object last( ): 最大值
SortedSet subSet(fromElement, toElement): 生成此set的子集,[from,to)
SortedSet headSet(toElement): 子集:由小于toElement的元素组成
SortedSet tailSet(fromElement):子集,由大于fromElement的元素组成

//: containers/SortedSetDemo.java
// What you can do with a TreeSet.
import java.util.*;
import static net.mindview.util.Print.*;
public class SortedSetDemo {
  public static void main(String[] args) {
    SortedSet<String> sortedSet = new TreeSet<String>();
    Collections.addAll(sortedSet,
      "one two three four five six seven eight"
        .split(" "));
    print(sortedSet);
    String low = sortedSet.first();//最小值
    String high = sortedSet.last();//最大值
    print(low);
    print(high);
    Iterator<String> it = sortedSet.iterator();
    for(int i = 0; i <= 6; i++) {
      if(i == 3) low = it.next();//fromElement
      if(i == 6) high = it.next();//lowElement
      else it.next();
    }
    print(low);
    print(high);
    print(sortedSet.subSet(low, high));//子集1
    print(sortedSet.headSet(high));//子集2
    print(sortedSet.tailSet(low));//子集3
  }
} /* Output:
[eight, five, four, one, seven, six, three, two]
eight
two
one
two
[one, seven, six, three]
[eight, five, four, one, seven, six, three]
[one, seven, six, three, two]
*///:~