HashSet集合用法
来源:互联网 发布:百度数据开放平台 编辑:程序博客网 时间:2024/05/21 10:46
|–Set:元素是无序(存入和取出的顺序不一定一致),元素不可以重复。、
|–HashSet:底层数据结构是哈希表。是线程不安全的。不同步。
HashSet是如何保证元素唯一性的呢?
是通过元素的两个方法,hashCode和equals来完成。
如果元素的HashCode值相同,才会判断equals是否为true。
如果元素的hashcode值不同,不会调用equals。
注意,对于判断元素是否存在,以及删除等操作,依赖的方法是元素的hashcode和equals方法。|--TreeSet:
Set集合的功能和Collection是一致的。
import java.util.*;class HashSetDemo { public static void sop(Object obj) { System.out.println(obj); } public static void main(String[] args) { HashSet hs = new HashSet(); sop(hs.add("java01")); sop(hs.add("java01")); hs.add("java02"); hs.add("java03"); hs.add("java03"); hs.add("java04"); Iterator it = hs.iterator(); while(it.hasNext()) { sop(it.next()); } }}
往hashSet集合中存入自定对象
姓名和年龄相同为同一个人,重复元素。
import java.util.*;class HashSetTest { public static void sop(Object obj) { System.out.println(obj); } public static void main(String[] args) { HashSet hs = new HashSet(); hs.add(new Person("a1",11)); hs.add(new Person("a2",12)); hs.add(new Person("a3",13));// hs.add(new Person("a2",12));// hs.add(new Person("a4",14)); //sop("a1:"+hs.contains(new Person("a2",12)));// hs.remove(new Person("a4",13)); Iterator it = hs.iterator(); while(it.hasNext()) { Person p = (Person)it.next(); sop(p.getName()+"::"+p.getAge()); } }}class Person{ private String name; private int age; Person(String name,int age) { this.name = name; this.age = age; } public int hashCode() { System.out.println(this.name+"....hashCode"); return name.hashCode()+age*37; } public boolean equals(Object obj) { if(!(obj instanceof Person)) return false; Person p = (Person)obj; System.out.println(this.name+"...equals.."+p.name); return this.name.equals(p.name) && this.age == p.age; } public String getName() { return name; } public int getAge() { return age; }}
0 0
- HashSet集合用法
- 集合之HashSet用法一
- java集合——HashSet的用法
- HashSet集合
- HashSet集合
- HashSet集合
- HashSet集合
- 集合 --- HashSet
- HashSet集合
- HashSet集合
- HashSet集合
- 集合-HashSet
- 集合中linkedlist与hashSet的用法与区别
- HashMap,Hashset,ArrayList以及LinkedList集合的区别和用法
- Java集合基础篇(3)-HashSet基本用法
- HashSet用法
- HashSet用法
- HashSet用法
- hadoop 压缩工具 比较
- 网易视频云技术分享:linux软raid的bitmap分析
- Spring 定时任务之 @Scheduled cron表达式
- bsurfaces插件
- hash算法 (hashmap 实现原理) Java实现的散列表
- HashSet集合用法
- C++Qt5调用 php-cgi.exe运行 php程序
- Fortran 函数中单精度,双精度不匹配的错误
- JAVA学习之——fail-fast机制
- Backbonejs之collection
- SVN常用终端命令
- Mysql运行sql文件出现错误1064
- (礼拜三log)前端开发:好用的日历插件推荐 plus table使用的注意事项
- 美化加载失败的图片(Stying broken images)