Java API —— Set接口 & HashSet类 & LinkedHashSet类
package setdemos;
import java.util.HashSet;
import java.util.Set;
/**
* Created by gao on 15-12-17.
*/
public class HashSetDemo01 {
public static void main(String[] args) {
//创建集合对象
Set<String> set = new HashSet<String>();
//创建并添加元素
set.add("hello");
set.add("java");
set.add("world");
set.add("java");
set.add("android");
set.add("hello");
//增强for
for(String s : set){
System.out.println(s);
}
}
}
package setdemos;
/**
* @author Administrator
*
*/
public class Student {
private String name;
private int age;
public Student() {
super();
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Student)) return false;
Student student = (Student) o;
if (age != student.age) return false;
if (!name.equals(student.name)) return false;
return true;
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + age;
return result;
}
}
测试类:
package setdemos;
import java.util.HashSet;
/**
* Created by gao on 15-12-17.
*/
/*
* 需求:存储自定义对象,并保证元素的唯一性
* 要求:如果两个对象的成员变量值都相同,则为同一个元素。
*
* 目前是不符合我的要求的:因为我们知道HashSet底层依赖的是hashCode()和equals()方法。
* 而这两个方法我们在学生类中没有重写,所以,默认使用的是Object类。
* 这个时候,他们的哈希值是不会一样的,根本就不会继续判断,执行了添加操作。
*/
public class HashSetDemo02 {
public static void main(String[] args) {
// 创建集合对象
HashSet<Student> hs = new HashSet<Student>();
// 创建学生对象
Student s1 = new Student("林青霞", 27);
Student s2 = new Student("柳岩", 22);
Student s3 = new Student("王祖贤", 30);
Student s4 = new Student("林青霞", 27);
Student s5 = new Student("林青霞", 20);
Student s6 = new Student("范冰冰", 22);
// 添加元素
hs.add(s1);
hs.add(s2);
hs.add(s3);
hs.add(s4);
hs.add(s5);
hs.add(s6);
// 遍历集合
for (Student s : hs) {
System.out.println(s.getName() + "---" + s.getAge());
}
}
}
interface Collection {
...
}
interface Set extends Collection {
...
}
class HashSet implements Set {
private static final Object PRESENT = new Object();
private transient HashMap<E,Object> map;
public HashSet() {
map = new HashMap<>();
}
public boolean add(E e) { //e=hello,world
return map.put(e, PRESENT)==null;
}
}
class HashMap implements Map {
public V put(K key, V value) { //key=e=hello,world
//看哈希表是否为空,如果空,就开辟空间
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
//判断对象是否为null
if (key == null)
return putForNullKey(value);
int hash = hash(key); //和对象的hashCode()方法相关
//在哈希表中查找hash值
int i = indexFor(hash, table.length);
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
//这次的e其实是第一次的world
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
//走这里其实是没有添加元素
}
}
modCount++;
addEntry(hash, key, value, i); //把元素添加
return null;
}
transient int hashSeed = 0;
final int hash(Object k) { //k=key=e=hello,
int h = hashSeed;
if (0 != h && k instanceof String) {
return sun.misc.Hashing.stringHash32((String) k);
}
h ^= k.hashCode(); //这里调用的是对象的hashCode()方法
// This function ensures that hashCodes that differ only by
// constant multiples at each bit position have a bounded
// number of collisions (approximately 8 at default load factor).
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
}
hs.add("hello");
hs.add("world");
hs.add("java");
hs.add("world");
4)HashSet存储元素保证唯一性的代码及图解

package hashsetdemos;
/**
* Created by gao on 15-12-17.
*/
public class Dog {
private String name;
private int age;
private String color;
private char sex;
public Dog() {
}
public Dog(String name, int age, String color, char sex) {
this.name = name;
this.age = age;
this.color = color;
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
", age=" + age +
", color='" + color + '\'' +
", sex=" + sex +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Dog)) return false;
Dog dog = (Dog) o;
if (age != dog.age) return false;
if (sex != dog.sex) return false;
if (!color.equals(dog.color)) return false;
if (!name.equals(dog.name)) return false;
return true;
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + age;
result = 31 * result + color.hashCode();
result = 31 * result + (int) sex;
return result;
}
}
测试类:
package hashsetdemos;
import java.util.HashSet;
/**
* Created by gao on 15-12-17.
*/
/*
* HashSet集合存储自定义对象并遍历。如果对象的成员变量值相同即为同一个对象
*
* 注意了:
* 你使用的是HashSet集合,这个集合的底层是哈希表结构。
* 而哈希表结构底层依赖:hashCode()和equals()方法。
* 如果你认为对象的成员变量值相同即为同一个对象的话,你就应该重写这两个方法。
* 如何重写呢?不同担心,自动生成即可。
*/
public class Exercise01 {
public static void main(String[] args) {
// 创建集合对象
HashSet<Dog> hs = new HashSet<Dog>();
// 创建狗对象
Dog d1 = new Dog("秦桧", 25, "红色", '男');
Dog d2 = new Dog("高俅", 22, "黑色", '女');
Dog d3 = new Dog("秦桧", 25, "红色", '男');
Dog d4 = new Dog("秦桧", 20, "红色", '女');
Dog d5 = new Dog("魏忠贤", 28, "白色", '男');
Dog d6 = new Dog("李莲英", 23, "黄色", '女');
Dog d7 = new Dog("李莲英", 23, "黄色", '女');
Dog d8 = new Dog("李莲英", 23, "黄色", '男');
//添加元素
hs.add(d1);
hs.add(d2);
hs.add(d3);
hs.add(d4);
hs.add(d5);
hs.add(d6);
hs.add(d7);
hs.add(d8);
//遍历
for (Dog d : hs) {
System.out.println(d.getName() + "---" + d.getAge() + "---" + d.getColor() + "---" + d.getSex());
}
}
}
package linkedhashset;
import java.util.LinkedHashSet;
/**
* Created by gao on 15-12-17.
*/
public class LinkedHashSetDemo {
public static void main(String[] args) {
// 创建集合对象
LinkedHashSet<String> hs = new LinkedHashSet<String>(); // 创建并添加元素
hs.add("hello");
hs.add("world");
hs.add("java");
hs.add("world");
hs.add("java");
// 遍历
for (String s : hs) {
System.out.println(s);
}
}
}
Java API —— Set接口 & HashSet类 & LinkedHashSet类的更多相关文章
- Java中的集合HashSet、LinkedHashSet、TreeSet和EnumSet(二)
Set接口 前面已经简绍过Set集合,它类似于一个罐子,一旦把对象'丢进'Set集合,集合里多个对象之间没有明显的顺序.Set集合于Collection基本上完全一样,它没有提供任何额外的方法. Se ...
- Java Set 常用集合 HashSet、LinkedHashSet、TreeSet
Java 中的 Set 是非常常用的数据类型.Set 是无序的 Collection,Java Set 有三个常用的实现类,分别是:HashSet.LinkedHashSet.TreeSet 本文基于 ...
- Java自学-集合框架 HashSet、LinkedHashSet、TreeSet之间的区别
HashSet. LinkedHashSet.TreeSet之间的区别 步骤 1 : HashSet LinkedHashSet TreeSet HashSet: 无序 LinkedHashSet: ...
- Java -- 获取指定接口的所有实现类或获取指定类的所有继承类
Class : ClassUtil package pri.lime.main; import java.io.File; import java.io.IOException; import jav ...
- Java API —— Map接口
1.Map接口概述 · 将键映射到值的对象 · 一个映射不能包含重复的键 · 每个键最多只能映射到一个值 2.Map接口和Collection接口的 ...
- Java API —— List接口&ListIterator接口
1.List接口概述 有序的 collection(也称为序列).此接口的用户可以对列表中每个元素的插入位置进行精确地控制.用户可以根据元素的整数索引(在列表中的位置)访问元素,并搜索 ...
- 获取Java接口的所有实现类
获取Java接口的所有实现类 前言:想看基于spring 的最简单实现方法,请直接看 第七步. 本文价值在于 包扫描的原理探究和实现 一.背景 项目开发中,使用Netty做服务端,保持长连接与客户端( ...
- Java 调用 Hbase API 访问接口实现方案
HBase是一个分布式的.面向列的开源数据库,该技术来源于 Fay Chang 所撰写的Google论文“Bigtable:一个结构化数据的分布式存储系统”.就像Bigtable利用了Google文件 ...
- Java 基础 - Set接口 及其实现类HashSet/LinkedHashSet/TreeSet
笔记: /**Set接口 及其实现类 * 公用操作同Collection: * * ①size(),clear()②isEmpty(),③contains(),④add()方法 和remove()方法 ...
随机推荐
- 查看leapmotion的frame信息
leapmotion的SDK里有个c#实例,很详细,其中的frame类已经把这些封装的很完善了.可惜是控制台的,运行时很难去找那些动作对应的哪些数据.我今天做的就是把它们在窗体控件里分别显示出来,这样 ...
- COUNT(*),count(1),COUNT(ALL expression),COUNT(DISTINCT expression)
创建一个测试表 IF OBJECT_ID( 'dbo.T1' , 'U' )IS NOT NULL BEGIN DROP TABLE dbo.T1; END; GO )); GO INSERT INT ...
- Oracle使用%type类型的变量输出结果
使用%type关键字可以声明一个与指定列名称相同的数据类型,他通常紧跟在指定列名的后面. 使用%type的2个好处: 1.用户不必查看表中各个列的数据类型,就可以确保所定义的变量能够存储检索的数据. ...
- Linux 批量解压gz包
[root@yoon export]# vi gunzip.sh !/bin/bashpath=/export/backup ----备份文件目录路径 for i in `ls ${path}/*`d ...
- OGG配置
准备安装和运行用户(操作系统用户) 建议使用oracle用户 也可以使用新建用户:但是需要做配置 必须缴入到oinstall 组 必须使用和oracle相同的profile 操作系统必须为该用户开放一 ...
- phpstrom 7.0 序列号
phpstrom 7.0 用户名 www.goipc.cn license key 13748-1204201000001dZdtN0KxZbl8zNH8RHFCz9t"gjKv9yXf2c ...
- Async详解之一:流程控制
为了适应异步编程,减少回调的嵌套,我尝试了很多库.最终觉得还是async最靠谱. 地址:https://github.com/caolan/async Async的内容分为三部分: 流程控制:简化十种 ...
- phpstorm8 设置及license key
phpstorm8 license key Learn Programming ===== LICENSE BEGIN ===== 63758-12042010 00000Ryqh0NCC73lpRm ...
- unity项目实现“再按一次退出程序”提示功能
unity项目,再按一次退出程序,按第一次做提示,再按一次,程序退出. float _waitTime = 2f;//前后两次按退出间隔时间 void OnGUI() { ) { GUI.Label( ...
- ibatis.net demo
1. download ibatis.nethttps://code.google.com/p/mybatisnet/ 2. add all dll as reference to your proj ...