Set

继承自Collection的一个接口,特点是:无序,不可重复。注意啊!!只有Collection实现了迭代器!也就是说Map是没有实现迭代器的,需要keySet,values,entrySet这个几个方法

HashSet实现Set接口

SortedSet继承自Set接口,无序,不可重复,但是可以存进去的元素可以自动按照大小进行排序。TreeSet是他的一个实现类。

HashSet的底层是一个HashMap。为什么?因为HashMap中的key无序,不可重复,跟HashSet有一样的特性,一个没有value的HashMap不就是一个HashSet?

public HashSet() {
map = new HashMap<>();
}

HashMap底层是一个哈希表

transient Node<K,V>[] table;

哈希表是什么?是数组和单向链表的结合

哈希表的本质是一个数组,只不过这个数组中的每一个元素又是单向链表。类似于现实世界中的字典。

static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next; Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
} ………
………
}

代码中的hash是key通过hashCode()方法,再通过哈希算法得到的一个值。在单向链表中,每一个结点的哈希值是相同的。

所以哈希表的查找过程是:通过key来得到哈希值,得到值后定位单向链表,然后遍历该链表。哈希表的增删效率都是比较高的。

向哈希表添加元素:通过key得到一个哈希值,如何在这个表中不存在这个值,就直接添加元素。否则,继续调用equals(),如果返回false则添加该元素,否则不添加,因为返回true的话证明里面已经有这个元素了。

HashSet是HashMap的key部分。

HashSet和HashMap的初始化容量是16 ,默认加载因子是0.75。比方说:容量是100,那么在装了75个元素的时候开始扩容

注意:存储在HashSet和HashMap中key部分的元素,需要重写hashCode()和equals();

public class HashSetTest {

    public static void main(String[] args) {
Set set = new HashSet();
Employee e1 = new Employee("24" , "KOBE");
Employee e2 = new Employee("21" , "TIM");
Employee e3 = new Employee("21" , "KG");
Employee e4 = new Employee("3" , "AI");
Employee e5 = new Employee("3" , "DW");
Employee e6 = new Employee("24" , "KOBE"); set.add(e1);
set.add(e2);
set.add(e3);
set.add(e4);
set.add(e5);
System.out.println("set.size = " + set.size()); // set.size = 5
} }
class Employee{
String no;
String name; public Employee(String no , String name){
this.no = no;
this.name = name;
} @Override
public int hashCode() {
return no.hashCode(); //String已经重写了hashCode方法,直接用它的
} @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj instanceof Employee){
Employee e = (Employee)obj;
if ( e.no.equals(this.no) && e.name.equals(this.name))
return true;
}
return false;
}
}

SortedSet存储元素为什么可以自动排序?如何实现的?

 public class SortedSetTest {

     public static void main(String[] args) {
User u1 = new User("kobe");
User u2 = new User("tim duncan");
User u3 = new User("ray allen");
User u4 = new User("melo"); SortedSet set = new TreeSet();
set.add(u1);
set.add(u2);
set.add(u3);
set.add(u4);
} } class User{
String name; public User(String name){
this.name = name;
} @Override
public String toString() {
return "[user name = " + name + "]";
}
}

上述代码运行时会报错:User cannot be cast to java.lang.Comparable

看下TreeSet的源码

public TreeSet() {
this(new TreeMap<E,Object>());
} public boolean add(E e) {
return m.put(e, PRESENT)==null;
}

发现底层是一个TreeMap。(其实跟HashSet类似,TreeSet也相当于TreeMap的key)

并且add()中是调用的TreeMap的put方法。这里再看下TreeMap的put方法源码。

public V put(K key, V value) {
……
……
else {
if (key == null)
throw new NullPointerException();
@SuppressWarnings("unchecked")
Comparable<? super K> k = (Comparable<? super K>) key; //强制转换成Compareble
do {
parent = t;
cmp = k.compareTo(t.key); //转换完后调用compareTo方法
if (cmp < 0) //小于0表示比根结点小,放左边
t = t.left;
else if (cmp > 0) //大于则放右边
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
……
}

那么需要去实现这个Compareble接口,并重写compareTo方法。

class User implements Comparable{
String name;
int age; public User(String name , int age){
this.name = name;
this.age = age;
} @Override
public String toString() {
return "[user name = " + name + " , age = " + age + "]";
} @Override //该方法程序员负责实现,sun(或者说现在要叫oracle了 :) )提供的程序调用了该方法。
public int compareTo(Object o) {
//编写一个比较规则 //根据年龄排序
int age1 = this.age;
int age2 = ((User)o).age;
return age1 - age2; //这个地方要注意只有在age的范围在一个足够小的时候才能这么干,如果age1是一个较大的整数,而age2是一个较小的负整数,age1-age2可能会溢出
/*
* [user name = melo , age = 2]
[user name = kobe , age = 10]
[user name = ray allen , age = 32]
[user name = tim duncan , age = 200]
*/
}
}

那么也可以按照名字来排序,String本身实现了compareble接口,所以可以直接用。

//根据名字来排序
return name.compareTo(((User)o).name);
/*
* [user name = kobe , age = 10]
[user name = melo , age = 2]
[user name = ray allen , age = 32]
[user name = tim duncan , age = 200]
*/

SortedSet实现排序还有一种方法,TreeSet中还有一个构造函数如下:

public TreeSet(Comparator<? super E> comparator) {
this(new TreeMap<>(comparator));
}

通过传入Comparator的实现类的参数来进行比较。

TreeMap中的put方法源码一部分如下:

Comparator<? super K> cpr = comparator;
if (cpr != null) {
do {
parent = t;
cmp = cpr.compare(key, t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}else{
//这个else是之前说的第一种方法,可以看到java是优先使用Comparator这种方法的 }

那么就写一个Comparator的实现类,并删掉之前User实现的Compareble接口以及compareTo方法。如果不删的话,结果也是一样的,因为java优先使用这种方法排序。其实也是推荐这种方式的,因为这样User就是一个更加纯粹的User。这种方式也可以写成匿名内部类的方式,不过为了代码的复用,最好还是单独写出来。

class UserComparator implements Comparator{
@Override
public int compare(Object o1, Object o2) {
int age1 = ((User)o1).age;
int age2 = ((User)o2).age; return age1 - age2;
}
}

[user name = melo , age = 2]
[user name = kobe , age = 10]
[user name = ray allen , age = 32]
[user name = tim duncan , age = 200]

Set笔记的更多相关文章

  1. git-简单流程(学习笔记)

    这是阅读廖雪峰的官方网站的笔记,用于自己以后回看 1.进入项目文件夹 初始化一个Git仓库,使用git init命令. 添加文件到Git仓库,分两步: 第一步,使用命令git add <file ...

  2. js学习笔记:webpack基础入门(一)

    之前听说过webpack,今天想正式的接触一下,先跟着webpack的官方用户指南走: 在这里有: 如何安装webpack 如何使用webpack 如何使用loader 如何使用webpack的开发者 ...

  3. SQL Server技术内幕笔记合集

    SQL Server技术内幕笔记合集 发这一篇文章主要是方便大家找到我的笔记入口,方便大家o(∩_∩)o Microsoft SQL Server 6.5 技术内幕 笔记http://www.cnbl ...

  4. PHP-自定义模板-学习笔记

    1.  开始 这几天,看了李炎恢老师的<PHP第二季度视频>中的“章节7:创建TPL自定义模板”,做一个学习笔记,通过绘制架构图.UML类图和思维导图,来对加深理解. 2.  整体架构图 ...

  5. PHP-会员登录与注册例子解析-学习笔记

    1.开始 最近开始学习李炎恢老师的<PHP第二季度视频>中的“章节5:使用OOP注册会员”,做一个学习笔记,通过绘制基本页面流程和UML类图,来对加深理解. 2.基本页面流程 3.通过UM ...

  6. NET Core-学习笔记(三)

    这里将要和大家分享的是学习总结第三篇:首先感慨一下这周跟随netcore官网学习是遇到的一些问题: a.官网的英文版教程使用的部分nuget包和我当时安装的最新包版本不一致,所以没法按照教材上给出的列 ...

  7. springMVC学习笔记--知识点总结1

    以下是学习springmvc框架时的笔记整理: 结果跳转方式 1.设置ModelAndView,根据view的名称,和视图渲染器跳转到指定的页面. 比如jsp的视图渲染器是如下配置的: <!-- ...

  8. 读书笔记汇总 - SQL必知必会(第4版)

    本系列记录并分享学习SQL的过程,主要内容为SQL的基础概念及练习过程. 书目信息 中文名:<SQL必知必会(第4版)> 英文名:<Sams Teach Yourself SQL i ...

  9. 2014年暑假c#学习笔记目录

    2014年暑假c#学习笔记 一.C#编程基础 1. c#编程基础之枚举 2. c#编程基础之函数可变参数 3. c#编程基础之字符串基础 4. c#编程基础之字符串函数 5.c#编程基础之ref.ou ...

  10. JAVA GUI编程学习笔记目录

    2014年暑假JAVA GUI编程学习笔记目录 1.JAVA之GUI编程概述 2.JAVA之GUI编程布局 3.JAVA之GUI编程Frame窗口 4.JAVA之GUI编程事件监听机制 5.JAVA之 ...

随机推荐

  1. 利用php函数mkdir递归创建层级目录

    项目开发中免不了要在服务器上创建文件夹,比如上传图片时的目录,模板解析时的目录等.这不当前手下的项目就用到了这个,于是总结了几个循环创建层级目录的方法. php默认的mkdir一次只能创建一层目录,而 ...

  2. select标签 样式 及文本有空格

    <s:select name="codeid" id="codeid" multiple="false"  list="#s ...

  3. Linux 安装 Redis 服务

    下载地址 http://download.redis.io/releases/redis-3.2.0.tar.gz 官网下载地址 http://redis.io/download 1.下载安装包 cd ...

  4. 关于Jsp页面在ww:iterator 标签里面判断的写法是可以直接写数组里面的变量的

    因为上面已经遍历了,所以可以直接写变量名

  5. windows cmd 命令大全

    原文: http://www.cnblogs.com/greatverve/archive/2011/12/09/windows-cmd.html 命令简介 cmd是command的缩写.即命令行 . ...

  6. CentOS 6.5 开机启动指定服务

    gedit /etc/rc.d/rc.local #关闭防火墙 service iptables stop #开启samba服务 service smb start #开启ntopng 端口5000 ...

  7. Rails (堆栈)<数据结构>

    题意:<看图片> 解题思路:栈的简单应用: #include<iostream> #include<stack> #include<algorithm> ...

  8. UIView的alpha、hidden、opaque 深入

    转载自:http://blog.csdn.net/wzzvictory/article/details/10076323 UIView的这几个属性让我困惑了好一阵子,通过翻看官方文档和stackove ...

  9. Divisor Summation_

    Divisor Summation Problem Description Give a natural number n (1 <= n <= 500000), please tell ...

  10. HDU 1251 统计难题(字典树计算前缀数量)

    字典树应用,每个节点上对应的cnt是以它为前缀的单词的数量 #include<stdio.h> #include<string.h> struct trie { int cnt ...