Java集合:Set集合的使用

王柳  金牌会员 | 2022-6-24 10:43:00 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 542|帖子 542|积分 1626

先看集合框架图:

Set有HashSet和TreeSet两种实现类。
先看Set:
特点:无序、无下标、元素不可重复
方法:全部继承自Collection中的方法
增、删、遍历、判断与collection一致
看代码:
  1. package com.collections.set;
  2. import java.util.HashSet;
  3. import java.util.Iterator;
  4. import java.util.Set;
  5. /**
  6. * set的使用
  7. * 特点:(1)无序(2)不能重复
  8. * @author 华子
  9. */
  10. public class Demo01 {
  11.     public static void main(String[] args) {
  12.         Set<String> set = new HashSet<>();
  13. //        添加
  14.         set.add("小米");
  15.         set.add("苹果");
  16.         set.add("华为");
  17.         set.add("华为");
  18.         System.out.println(set.size());
  19.         System.out.println(set.toString());
  20. //        删除
  21. //        set.remove("苹果");
  22. //        System.out.println("删除后:"+set.size());
  23. //        System.out.println(set.toString());
  24. //        遍历
  25. //       增强for
  26.         for (String s :set
  27.              ) {
  28.             System.out.println(s);
  29.         }
  30.         System.out.println("------------------------");
  31. //        迭代器
  32.         Iterator<String> iterator = set.iterator();
  33.         while (iterator.hasNext()){
  34.             String s = iterator.next();
  35.             System.out.println(s);
  36.         }
  37.         System.out.println("------------------------");
  38.         for (String s :set) {
  39.             System.out.println(s);
  40.         }
  41. //        判断
  42.         System.out.println(set.contains("华为"));
  43.         System.out.println(set.isEmpty());
  44.     }
  45. }
复制代码
和之间的集合使用方法类似。
HasSet【重点】

存储结构:哈希表(数组+链表+红黑树)
存储过程(重复依据)

  • 根据hashCode计算保存的位置,如果位置为空,直接保存,若不为空,进行第二步
  • 再执行equals方法,如果equals为true,则认为是重复,否则形成链表
特点
存储过程:
<ul>基于HashCode计算元素存放位置   <ul>
利用31这个质数,减少散列冲突     <ul>
31提高执行效率 31 * i = (i
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

王柳

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表