通过HashSet达到对象集去重的实现(jdk1.8)
通过HashSet达到对象集去重的实现(jdk1.8)
public class Contract {
private String contractId;
private String contractName;
private Date begin;
private Date end;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Contract contract = (Contract) o;
//自己的判断条件是时间段重合的算做同一个对象
return false;
}
@Override
public int hashCode() {
//通过Objects类提供的hash方法
int hash = Objects.hash(contractId, contractName);
return hash;
}
public class Test {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
Contract c1 = new Contract();
c1.setContractName("c");
c1.setContractId("1");
c1.setBegin(calendar.getTime());
calendar.set(Calendar.DAY_OF_MONTH,calendar.get(Calendar.DAY_OF_MONTH)+1);
c1.setEnd(calendar.getTime());
/* */
Contract c2 = new Contract();
c2.setContractName("c");
c2.setContractId("1");
calendar.setTime(new Date());
c2.setBegin(calendar.getTime());
calendar.set(Calendar.DAY_OF_MONTH,calendar.get(Calendar.DAY_OF_MONTH)+2);
c2.setEnd(calendar.getTime());
HashSet<Contract> set = new HashSet<>();
set.add(c1);
set.add(c2);
System.out.println(set.size());
}
}
1.HashSet内部维护类了一个HashMap,可以看到默认的构造方法其实就是实例化了一个hashMap
private transient HashMap<E,Object> map;
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
/**
* Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
* default initial capacity (16) and load factor (0.75).
*/
public HashSet() {
map = new HashMap<>();
}
/**
* Constructs a new set containing the elements in the specified
* collection. The <tt>HashMap</tt> is created with default load factor
* (0.75) and an initial capacity sufficient to contain the elements in
* the specified collection.
*
* @param c the collection whose elements are to be placed into this set
* @throws NullPointerException if the specified collection is null
*/
public HashSet(Collection<? extends E> c) {
map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
addAll(c);
}
2.在添加对象的时候判断了对象是否的hashCode是否相等,如果相等需要进一步判断对象的equals方法
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
通过HashSet达到对象集去重的实现(jdk1.8)的更多相关文章
- Set\HashSet集合为什么能去重(转)
如果想查找一个集合中是否包含有某个对象,大概的程序代码怎样写呢?当发现某个元素与要查找的对对象进行equals方法比较的结果相等时,则停止继续查找并返回肯定的信息,否则返回否定的信息.如果是一个集合中 ...
- MapReduce算法形式二:去重(HashSet)
案例二:去重(shuffle/HashSet等方法)shuffle主要针对的是key去重HashSet主要针对values去重
- [JAVA]JAVA章1 数组数据去重
一 利用HashSet进行去重 //定义一个数组:有几个重复项 int[] testarray = {1,2,33,4,2,3,44,5,222,3}; //利用HashSet对数组数据去重 Set& ...
- Java使用极小的内存完成对超大数据的去重计数,用于实时计算中统计UV
Java使用极小的内存完成对超大数据的去重计数,用于实时计算中统计UV – lxw的大数据田地 http://lxw1234.com/archives/2015/09/516.htm Java使用极小 ...
- MapReduce算法形式二:去重(shuffle)
案例二:去重(shuffle/HashSet等方法)shuffle主要针对的是key去重HashSet主要针对values去重
- java list去重操作实现方式
Java中的List是可以包含重复元素的(hash code 和equals),接下来将介绍两种方式实现java list去重操作,感兴趣的朋友可以参考下 Java中的List是可以包含重复元素的 ...
- 一、基础篇--1.2Java集合-HashMap和HashSet的区别
HashMap和HashSet的区别 1.HashMap实现的是Map接口,HashSet实现的是Set接口 2.结构不一样,一个存储的是键值对,一个存储的是对象 3.HashMap存储的值可能相同 ...
- C#黔驴技巧之去重(Distinct)
前言 关于C#中默认的Distinct方法在什么情况下才能去重,这个就不用我再多讲,针对集合对象去重默认实现将不再满足,于是乎我们需要自定义实现来解决这个问题,接下来我们详细讲解几种常见去重方案,孰好 ...
- 面试官:HashSet如何保证元素不重复?
本文已收录<Java常见面试题>系列,Git 开源地址:https://gitee.com/mydb/interview HashSet 实现了 Set 接口,由哈希表(实际是 HashM ...
随机推荐
- 使用ThreadPoolExecutor进行多线程编程
ThreadPoolExecutor有四个构造函数,分别是: 1,ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keep ...
- FIN_WAIT_2状态解释
关于网络设备的FIN_WAIT_2状态解释出处:http://hi.baidu.com/netdemon1981/blog/item/584bfbb2aeb1d4acd9335ad9.html 在HT ...
- pytorch安装 caffe2 安装:git 慢 caffe2 cannot find -lopencv_dep_cudart ,undefined reference to 'pthread_create'
最开始的问题: caffe2目前已经不维护了.怎么编译都报错,并且有third_party的代码链接已经飞了.下载不全代码了.建议 不要再折腾了,直接安装Pytorch. 首先,基本环境是ubuntu ...
- python读取excel,返回dic列表
def get_xls_sheets_as_dic(pro_name, xls_name): dic_list = [] xls_path = os.path.join(BASE_PATH, &quo ...
- sql 日志文件截断收缩
use mydb ALTER DATABASE mydb SET RECOVERY SIMPLE WITH NO_WAIT ALTER DATABASE mydb SET RECOVERY SIMPL ...
- Axis2 服务器端抛出ServiceClass object does not implement问题解决方法
在用eclipse配合Axis2进行开发的时候,编译通过,启动tomcat也顺利,但是就是在调用服务器端的服务时,会抛出: The ServiceClass object does not imple ...
- Nginx之 try_files 指令
location / { try_files $uri $uri/ /index.php; } 当用户请求 http://localhost/example 时,这里的 $uri 就是 /exampl ...
- mysql导入太慢解决方法
半调子数据科学家又要折腾数据,拿到数据一看,3.6G的zip文件,解压看看,卧槽12个G的sql文件.好吧,又要折腾sql数据了.第一件事,肯定是搭一个数据库,导入数据咯. 折腾过sql导入的亲们都知 ...
- Redis 数据类型归纳
Redis的数据类型从整体上看,都是Key-Value键值对的模型,数据类型更确切地说,应该是Value的数据类型,比如string,set,list等,都是key值对应的Value的数据集合格式.不 ...
- ArcGIS案例教程-通过点坐标生成矩形
ArcGIS案例教程-通过点坐标生成矩形 联系方式:谢老师,135-4855-4328,xiexiaokui#qq.com 功能:以点坐标为中心,通过指定尺寸,生成矩形 成果形式:绿色工具,免安装,不 ...