集合—HashSet
对于 HashSet 而言,它是基于 HashMap 实现的,底层采用 HashMap 来保存元素,所以如果对 HashMap 比较熟悉了。
HashSet和ArrayList区别:
HashSet无序不可重复,ArrayLIst有序可重复
HashSet(无序不重复)
1.add方法
//以下会去掉重复值 hashSet.add(100); hashSet.add(100); System.out.println(hashSet); //只会输出一个100,并且没有get方法,因为无序不知道怎么获取
例:list去重
注:以下方法不可以,remove之后长度就变了,因为集合长度是变长的,所以这个方法不可行
//list集合去重 ArrayList<String> arrayList = new ArrayList<String>(); arrayList.add("ddd"); arrayList.add("hhh"); arrayList.add("zs"); arrayList.add("zs"); arrayList.add("zl"); arrayList.add("zl"); for (int i = 0; i < arrayList.size(); i++) { String string = arrayList.get(i); if(arrayList.contains(string)) { arrayList.remove(string); } }
用下面方法,直接list集合转化为set集合,因为set本身就是去重
ArrayList<String> arrayList = new ArrayList<String>(); arrayList.add("ddd"); arrayList.add("hhh"); arrayList.add("zs"); arrayList.add("zs"); arrayList.add("zl"); arrayList.add("zl"); HashSet<String> hashSet = new HashSet<String>(); for (String string : arrayList) { hashSet.add(string); } System.out.println(hashSet); //输出[zl, ddd, hhh, zs],会将重复值去掉
2.size方法输出元素个数大小
ArrayList<Integer> arrayList = new ArrayList<Integer>(); arrayList.add(11); arrayList.add(22); arrayList.add(33); System.out.println("大小个数"+arrayList.size()); //输出3
3.isEmpty方法和contains方法
ArrayList<Integer> arrayList = new ArrayList<Integer>(); arrayList.add(11); arrayList.add(22); arrayList.add(33); System.out.println("是否为空"+arrayList.isEmpty()); System.out.println("是否包含"+arrayList.contains(55)); //输出两个false 不为空和不包含55
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?