[关闭]
@liruiyi962464 2017-03-21T04:00:33.000000Z 字数 2199 阅读 469

集合(Set)

java

遍历方法

  • ArrayList LinkedList三种方式都能使用
  • HashSet TreeSet没有办法使用for,foreach循环的底层是有迭代器实现的,能用迭代器遍历就能用foreach
  • 凡是能用foreac遍历的都能用迭代器遍历
  1. HashSet<String> hashSte = new HashSet<String>();
  2. hashSte.add("张三");
  3. hashSte.add("李四");
  4. hashSte.add("王五");
  5. //直接输出
  6. System.out.println(hashSte.hashSte(i));
  7. // foreach
  8. for (String string : hashSte) {
  9. System.out.println(string);
  10. }
  11. // 迭代器 (Iterator)
  12. //(hasNext:是否有数据存在)(next:迭代输出)
  13. System.out.println("迭代器遍历");
  14. Iterator<String> iterator = hashSte.iterator();
  15. while(iterator.hasNext()){
  16. System.out.println(iterator.next());
  17. }
  18. //迭代器(for)
  19. for (Iterator iterator = arratList.iterator(); iterator.hasNext();) {
  20. System.out.println(iterator.next());
  21. }

HashSet

  • 创建一个类集,使用散射表(又称哈希表)进行存储
  • 没有确保其元素的顺序,因为散列处理通常不参与排序

HashSet实例

  1. HashSet<String> hashSte = new HashSet<String>();
  2. //添加
  3. System.out.println(hashSte.add("a"));
  4. System.out.println(hashSte.add("d"));
  5. System.out.println(hashSte.add("a"));
  6. System.out.println(hashSte.add("b"));
  7. System.out.println(hashSte.add("b"));
  8. System.out.println(hashSte);
  9. //查询
  10. System.out.println(hashSte.contains("c"));
  11. //查看是否包含指定元素
  12. System.out.println(hashSte.isEmpty()+""+hashSte);
  13. //返回对此 set 中元素进行迭代的迭代器。
  14. Iterator<String> it = hashSte.iterator();
  15. while(it.hasNext()){
  16. System.out.println(it.next());
  17. }
  18. //删除
  19. System.out.println(hashSte.remove("a")+""+hashSte);
  20. //返回此 set 中的元素的数量(set 的容量)。
  21. System.out.println(hashSte.size());
  22. //清除
  23. hashSte.clear();
  24. System.out.println(hashSte);

TreeSet

  • 对象按照升序存储,访问和检索很快
  1. TreeSet<String> treeSet=new TreeSet<String>();
  2. treeSet.add("qwe");
  3. treeSet.add("asd");
  4. treeSet.add("zxc");
  5. treeSet.add("rty");
  6. treeSet.add("fgh");
  7. System.out.println(treeSet);
  8. //如果此 set 包含指定的元素,则返回 true。
  9. System.out.println(treeSet.contains("qwe"));
  10. //迭代器输出
  11. Iterator<String> it = treeSet.iterator();
  12. while(it.hasNext()){
  13. System.out.print(it.next()+"\t");
  14. }
  15. System.out.println();
  16. //foreach 没有办法使用for,foreach循环的底层是有迭代器实现的,能用迭代器遍历就能用foreach
  17. for (String string : treeSet) {
  18. System.out.print(string+"\t");
  19. }
  20. System.out.println();
  21. //返回此 set 中当前第一个(最低)元素。
  22. System.out.println(treeSet.first());
  23. //返回此 set 中小于等于给定元素的最大元素;如果不存在这样的元素,则返回 null。
  24. System.out.println(treeSet.floor("asd"));
  25. //如果此 set 不包含任何元素,则返回 true。
  26. System.out.println(treeSet.isEmpty());
  27. // 返回此 set 的部分视图,其元素范围从 fromElement 到 toElement。
  28. System.out.println(treeSet.subSet("a", "z"));
  29. //返回此 set 的部分视图,其元素大于等于 fromElement。
  30. System.err.println(treeSet.tailSet("b"));
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注