`
xuanzhui
  • 浏览: 197029 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

关于Set和Map的注意事项

阅读更多

1. HashSet和HashMap

public boolean add(E e)

Adds the specified element to this set if it is not already present. More formally, adds the specified element e to this set if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false.

 
public V put(K key, V value)
Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.
 
set add如果是相同的那么忽略新的,老的保持不变
map put如果是相同的key,那么更新老的value
 
hash类型的set和map判断相同的标准是equals,但是也可能为了优化性能先用hashCode进行了过滤,因为如果equals是true的话,要保证这两个object的hashCode是相等的
refer 
 
默认情况下,new出来的对象都是不equals的,hashCode也是不相等的,实际上就是和创建出来的对象内存地址相关的
equals:
The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).
 
hashCode:
As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)
 
所以,如果想要自定义一个对象的比较方式需要手动同时实现equals和hashCode
例如,如下的AppInfo希望set里面保留的都是id不同的对象
public static void main(String[] args) {
    AppInfo app1 = new AppInfo();
    app1.id = "id-1";
    app1.totalCount = 1;

    AppInfo app2 = new AppInfo();
    app2.id = "id-2";
    app2.totalCount = 2;

    AppInfo app3 = new AppInfo();
    app3.id = "id-1";
    app3.totalCount = 3;

    Set<AppInfo> set = new HashSet<>();
    set.add(app1);
    set.add(app2);
    set.add(app3);

    for (AppInfo app : set) {
        System.out.println(String.format("[%s, %d]", app.id, app.totalCount));
    }
}

static class AppInfo {
    public String id;
    public int totalCount;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        AppInfo appInfo = (AppInfo) o;

        return id.equals(appInfo.id);
    }

    @Override
    public int hashCode() {
        return id.hashCode();
    }
}
 结果是
[id-2, 2]
[id-1, 1]
 
2. TreeSet和TreeMap
TreeSet的内部元素是有序的,TreeMap的内部元素key是有序的
这两种类型的数据结构并不会关注equals,而是直接通过Comparator的compare结果,或者是实现Comparable的compareTo结果来判定是否是重复的元素
比如下面直接通过AppInfo的totalCount比较实现排序
public static void main(String[] args) {
    AppInfo app1 = new AppInfo();
    app1.id = "id-1";
    app1.totalCount = 1;

    AppInfo app2 = new AppInfo();
    app2.id = "id-2";
    app2.totalCount = 2;

    AppInfo app3 = new AppInfo();
    app3.id = "id-3";
    app3.totalCount = 2;

    //java8的lambda创建Comparator
    Map<AppInfo, String> map = new TreeMap<>((left, right) -> left.totalCount - right.totalCount);
    map.put(app1, "value1");
    map.put(app2, "value2");
    map.put(app3, "value3");

    for (AppInfo app : map.keySet()) {
        System.out.println(String.format("[%s, %d] --> %s", app.id, app.totalCount, map.get(app)));
    }
}

static class AppInfo {
    public String id;
    public int totalCount;
}
 结果为
[id-1, 1] --> value1
[id-2, 2] --> value3
分享到:
评论

相关推荐

    ES6中Set和Map用法实例详解

    主要介绍了ES6中Set和Map用法,结合实例形式详细分析了ES6中Set和Map的基本功能、原理、使用方法及操作注意事项,需要的朋友可以参考下

    ES6中Symbol、Set和Map用法详解

    主要介绍了ES6中Symbol、Set和Map用法,结合实例形式详细分析了ES6中Symbol、Set和Map的功能、使用方法及相关操作注意事项,需要的朋友可以参考下

    ES6学习笔记之Set和Map数据结构详解

    主要介绍了ES6学习笔记之Set和Map数据结构,结合实例形式详细分析了ECMAScript中基本数据结构Set和Map的常用属性与方法的功能、用法及相关注意事项,需要的朋友可以参考下

    ES6教程之for循环和Map,Set用法分析

    主要介绍了ES6教程之for循环和Map,Set用法,结合实例形式分析了ECMAScript6中for循环和Map,Set基本概念、功能、使用方法与相关注意事项,需要的朋友可以参考下

    Java集合定义与用法实例总结【Set、List与Map】

    主要介绍了Java集合定义与用法,结合实例形式总结分析了Java集合中Set、List和Map相关概念、功能、用法及操作注意事项,需要的朋友可以参考下

    art_map:实验性病

    介绍 该库是C ++ 14模板库,...注意事项 在ART中可以使用哪种键是有限制的。 键必须可转换为BitwiseComparable ,并保持std::less或std::greater施加的顺序。 已经提供了整数键类型,指针和std::string (在std::les

    Java面试八股文.zip

    1.2 面试流程和注意事项 1.3 自我介绍及项目介绍 1.4常见面试问题 2. Redis篇 2.1 Redis简介和特点 2.2 Redis数据类型及其应用 2.3 Redis持久化机制 2.4 Redis高级特性和集群 3. MySQL数据库篇 3.1 MySQL...

    单相机标定 标定板标定和自标定.rar

    单相机标定,标定板标定和自标定实例源码。初始参数的说明和获取方法, set_origin_pose() 参数的计算方法, gen_image_to_world_plane_map() 参数Scale的计算方法, 问题说明 注意事项

    基于OFDM系统PAPR算法MATLAB性能仿真,对比SLM和PTS【包含程序操作录像,代码部分注释】

    1.版本:matlab2022A,包含仿真操作录像,操作录像使用windows media player播放。 2.领域:PAPR ...4.注意事项:注意MATLAB左侧当前文件夹路径,必须是程序所在文件夹位置,具体可以参考视频录。

    STL设计原理和使用

    介绍STL设计原理和使用 STL概览 迭代器 迭代器适配器 容器 序列式容器-vector、list、deque、string 关联式容器-map、set、multimap、multiset 算法和函数对象 函数对象适配器 STL使用注意事项

    java内部学习笔记.docx

    2.16 Java基础其他注意事项 14 面向对象 16 3.1类 16 3.2对象 16 3.3包 16 3.4方法及其调用 17 3.5引用 17 3.6访问控制(封装) 17 3.7构造器 17 3.8 super()、super.和 this()、this. 18 3.9重载和重写 19 3.10...

    kubernetes-learning.pdf

    Helm 模板之其他注意事项 Helm Hooks 调度器 Kubernetes 调度器介绍 Kubernetes 亲和性调度 集群监控 ⼿动安装 Prometheus 监控 Kubernetes 集群应⽤ 监控 Kubernetes 集群节点 监控 Kubernetes 常⽤资源对象 ...

    在线考试系统

    注意事项:数据库中的数据 因为所有的考试试卷是放到tomcat的安装路径的: 例如安装路径为d盘: D:\apache-tomcat-6.0.16\webapps\online_exam\paper 所以要把数据库中paper_list表中的paper_path路径要换成 tomcat...

    effective stl stl 技巧

    条款1:仔细选择你的容器 条款2:小心对“容器无关代码”的幻想 条款3:使容器里对象的拷贝操作轻量而正确 条款4:用empty来代替检查size()是否为0 ...附录B:在微软STL平台上的注意事项 词汇表 索引

    Effective STL(中文)

    不知道网上有没有Effective STL(中文),我找不到,我自己整理出了这个《Effective STL(中文)》共享给需要...区域设置和忽略大小写的字符串比较 附录B:在微软STL平台上的注意事项 词汇表 索引 关于本电子书

    CuckooMap:使用布谷鸟哈希的HashMap的Python实现

    一些注意事项: 有时,使用杜鹃哈希,set()函数会变成无限循环(如Wikipedia文章所述)。 为了解决这个问题,我选择定义一个函数来检测是否有超过2000个基因剔除。 一旦达到此限制,我将拒绝二传手。 拒绝不会...

    Docker到Kubernetes进阶视频.rar

    │ │ 47.Helm 模板之其他注意事项.mp4 │ └ 48.Helm Hooks 的使用.mp4 ├ 十三、集群监控 │ │ 52.手动安装 Prometheus.mp4 │ │ 53.Prometheus 安装错误排查.mp4 │ │ 54.监控 Kubernetes 集群应用.mp4 │ │ ...

    egmap:面向对象PHP抽象到Google Maps API,以简化在Yii项目中添加Google Map的过程

    现在,魔术获取器和设置器允许使用名称或名称预先设置为set或get的选项和函数(如属性),或多或少地使用CComponent。 该版本具有(包括所有以前的库): LatLonControl DragKeyZoom控件 MarkerWithLabel控件 ...

    百度地图 功能模块完整版 开发指南

    (6)其他注意事项请参考【CloudSearchDemoViewController.mm文件内的注释部分】; (7)LBS.云检索使用方法请参考开发指南“LBS云服务”部分; (8)详细了解LBS.云,欢迎访问:...

    ES6学习笔记之新增数据类型实例解析

    主要介绍了ES6学习笔记之新增数据类型,结合实例形式分析了ES6数据解构赋值、新增数据类型Set集合、新增数据类型Map、Symbol类型等相关原理与操作注意事项,需要的朋友可以参考下

Global site tag (gtag.js) - Google Analytics