Set - 图1

常见方法

  1. import java.util.HashSet;
  2. import java.util.Set;
  3. public class SetTest {
  4. public static void main(String[] args) {
  5. Set<String> s = new HashSet();
  6. s.add("john");
  7. s.add("maria");
  8. s.add("jack");
  9. System.out.println(s.contains("john"));
  10. s.remove("jack");
  11. for(String s2 : s ){
  12. System.out.println(s2);
  13. }
  14. }
  15. }

实现接口

TreeSet

  1. import java.util.Comparator;
  2. import java.util.Set;
  3. import java.util.TreeSet;
  4. public class TreeSetTest {
  5. public static void main(String[] args) {
  6. Set<Students> s = new TreeSet<>(new Comparator<Students>() {
  7. @Override
  8. public int compare(Students s1, Students s2) {
  9. return s1.name.compareTo(s2.name);
  10. }
  11. });
  12. }
  13. }

总结

Set接口并不保证有序,而SortedSet接口则保证元素是有序的:

  • HashSet是无序的,因为它实现了Set接口,并没有实现SortedSet接口;
  • TreeSet是有序的,因为它实现了SortedSet接口。