java 集合之Set
来源:互联网 发布:抢牛牛神器软件 编辑:程序博客网 时间:2024/05/16 12:55
Set的特点是 无序,无下标,元素不可重复,我们看一下它的实现类
HashSet
public static void main(String[] args) {Set<String> set = new HashSet<String>();set.add("1");}当我们new 一个HashSet的时候
/** * 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<>(); }其他就是new 了一个HashMap,我们add的时候,
/** * Adds the specified element to this set if it is not already present. * More formally, adds the specified element <tt>e</tt> to this set if * this set contains no element <tt>e2</tt> such that * <tt>(e==null ? e2==null : e.equals(e2))</tt>. * If this set already contains the element, the call leaves the set * unchanged and returns <tt>false</tt>. * * @param e element to be added to this set * @return <tt>true</tt> if this set did not already contain the specified * element */ public boolean add(E e) { return map.put(e, PRESENT)==null; }
其实就是将我们要放入的元素作为map的key存放,value是一个object对象
// Dummy value to associate with an Object in the backing Map private static final Object PRESENT = new Object();其他的它底层实现就是HashMap,我们知道HashMap的键对象,存储是根据哈希算法,具体可以参考我的另一篇文章
http://blog.csdn.net/xu511739113/article/details/52366754
所以如果是自定义的对象,我们需要重写equals和hashCode方法。
LinkedHashSet的特点是可以保留插入顺序。要注意,如果要使用LinkedHashSet也需要重写equals和hashCode方法。
0 0
- JAVA集合之SET
- java集合之Set
- Java集合之set
- Java集合之Set
- Java集合之Set
- Java集合之set
- Java集合之Set
- java集合之Set
- java集合之Set
- java 集合之Set
- Java集合之Set
- Java集合之Set
- Java之集合Set
- Java集合之Set
- Java集合之Set集合
- Java集合之Set集合
- (转) Java集合之Set
- Java集合之Set探讨
- 对寄存器操作的通用方法总结
- CSS 边框(20160821-0021)
- 167. Two Sum II - Input array is sorted
- postgres 安装及配置(ubuntu)
- 优化Mysql数据库的8个方法
- java 集合之Set
- AFNetWork请求Cache问题
- spring mvc与html中处理引用js等静态文件的问题
- 知乎大神关于高级ios进阶
- Windows之修改鼠标或触控板的滚轮方向
- redisUtil
- androidstudio腾讯地图集成定位绘制行走过的路线
- tjut 3508
- spring-boot-starter-logging logback配置之<configuration><logger>标签详解