通过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)的更多相关文章

  1. Set\HashSet集合为什么能去重(转)

    如果想查找一个集合中是否包含有某个对象,大概的程序代码怎样写呢?当发现某个元素与要查找的对对象进行equals方法比较的结果相等时,则停止继续查找并返回肯定的信息,否则返回否定的信息.如果是一个集合中 ...

  2. MapReduce算法形式二:去重(HashSet)

    案例二:去重(shuffle/HashSet等方法)shuffle主要针对的是key去重HashSet主要针对values去重

  3. [JAVA]JAVA章1 数组数据去重

    一 利用HashSet进行去重 //定义一个数组:有几个重复项 int[] testarray = {1,2,33,4,2,3,44,5,222,3}; //利用HashSet对数组数据去重 Set& ...

  4. Java使用极小的内存完成对超大数据的去重计数,用于实时计算中统计UV

    Java使用极小的内存完成对超大数据的去重计数,用于实时计算中统计UV – lxw的大数据田地 http://lxw1234.com/archives/2015/09/516.htm Java使用极小 ...

  5. MapReduce算法形式二:去重(shuffle)

    案例二:去重(shuffle/HashSet等方法)shuffle主要针对的是key去重HashSet主要针对values去重

  6. java list去重操作实现方式

    Java中的List是可以包含重复元素的(hash code 和equals),接下来将介绍两种方式实现java list去重操作,感兴趣的朋友可以参考下   Java中的List是可以包含重复元素的 ...

  7. 一、基础篇--1.2Java集合-HashMap和HashSet的区别

     HashMap和HashSet的区别 1.HashMap实现的是Map接口,HashSet实现的是Set接口 2.结构不一样,一个存储的是键值对,一个存储的是对象 3.HashMap存储的值可能相同 ...

  8. C#黔驴技巧之去重(Distinct)

    前言 关于C#中默认的Distinct方法在什么情况下才能去重,这个就不用我再多讲,针对集合对象去重默认实现将不再满足,于是乎我们需要自定义实现来解决这个问题,接下来我们详细讲解几种常见去重方案,孰好 ...

  9. 面试官:HashSet如何保证元素不重复?

    本文已收录<Java常见面试题>系列,Git 开源地址:https://gitee.com/mydb/interview HashSet 实现了 Set 接口,由哈希表(实际是 HashM ...

随机推荐

  1. javascript基础知识笔记-自用

    笔记内容根据个人基础知识不足不明白之处做的记录.主要看的:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript 1.变量,变量的名字又叫标识符 ...

  2. mac电脑复制键失灵

    mac键按command+c偶尔失灵打电话给客服. 客服的解决方案: 1.关机状态同时按: shiflt+option+control+关机键  (重置键盘快捷键不会丢失数据)  20秒 2.松开后重 ...

  3. thinkphp5.1 的else if的使用方法

    首先thinkphp5.1获取session值是 {$think.session.user_id}或者{$Request.session.user_id}来获取session 下面是if else 的 ...

  4. Unable to docker login through CLI - unauthorized: incorrect username or password

    Unable to docker login through CLI - unauthorized: incorrect username or password To solve it proper ...

  5. 获取用户登陆所在的ip及获取所属信息

    package com.tcl.topsale.download.entity; public class GeoLocation { private String countryCode; priv ...

  6. list之flex布局写法

    list之flex布局写法 移动端实际场景中经常会遇到将header置顶,然后下面list需要滚动的情况,通常的做法会是将header使用fixed的方式固定到顶部,然后list主体相对于header ...

  7. Angular开发环境构筑

    今天按照下面的顺序构筑了Angular的开发环境.很简单. -- 系统:win7, 64位 1.安装Note 从<https://nodejs.org/ja/>下载安装文件,安装. Not ...

  8. 解决laravel使用QQ邮箱发邮件失败

    在 laravel 中使用 QQ 发送邮件的时候莫名其妙的出现了如下错误:Connection could not be established with host smtp.exmail.qq.co ...

  9. Unreal4360全景视频序列渲染

    Unreal4 自带360全景渲染的插件 插件名称叫 Stereo Panoramic Movie Capture 一.打开Edit下的Plugins 二.搜索Stereo Panoramic Mov ...

  10. celery (二) task调用

    调用 TASK 基础 task 的调用方式有三种: 类似普通函数的调用方式, 通过 __calling__ 调用 ,类似 function() 通过 apply_async() 调用,能接受较多的参数 ...