• HashSet


    HashSet的底层数据结结构是哈希表,哈希表用于存储哈希值,

        hashSet中比较对象是否一样的是自动调用对象的hashCode和equals方法(hash值是操作系统给的,equals是Object继承的。自己也可以重写),当hash值相同时才调用equals,否则不要调用,只有当hashcode与equals值都相等是才视为同一对象。String类重新了equals方法。所以一般用hashSet时,要对类重写hashCode 和equals方法。

    /

    未重写时比较的是地址==。内容一样也会存进去

    /

    public class HashSetTest {

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    Set s = new HashSet();
    s.add(new Person5("xiaoli",23));
    s.add(new Person5("xiaoli",23));
    s.add(new Person5("xiaoli",23));
    s.add(new Person5("xiaoli",23));
    Iterator it = s.iterator();
    while(it.hasNext()){
    Person5 p1 =(Person5)it.next();
    System.out.println(p1.getName()+"----"+p1.getAge());
    }
    }

    }

    class Person5 {
    private String name;
    private int 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;
    }
    public Person5(String name, int age) {
    super();
    this.name = name;
    this.age = age;
    }

    }

    结果是:

    xiaoli----23
    xiaoli----23
    xiaoli----23
    xiaoli----23

    /**

    重写hashCode和equals后:

    **/


    public class HashSetTest {

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    Set s = new HashSet();
    s.add(new Person5("xiaoli",23));
    s.add(new Person5("xiaoli",23));
    s.add(new Person5("xiaoli",23));
    s.add(new Person5("xiaoli",23));
    Iterator it = s.iterator();
    while(it.hasNext()){
    Person5 p1 =(Person5)it.next();
    System.out.println(p1.getName()+"----"+p1.getAge());
    }
    }

    }

    class Person5 {
    private String name;
    private int 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;
    }
    public Person5(String name, int age) {
    super();
    this.name = name;
    this.age = age;
    }

    public int hashCode(){
    return this.age;

    }

    public boolean equals(Object o){
    Person5 p =(Person5)o;
    if(!(p instanceof Person5))
    return false;
    return this.name.equals(p.name);
    }

    }

    结果是:

    xiaoli----23

  • 相关阅读:
    AI智能视频平台如何切换人脸识别算法?
    AI智能识别技术在明厨亮灶场景中的应用
    利用GO集成百度AI人脸识别算法的开发实践
    win10子系统中访问linux文件
    Go常用依赖注入框架需要注意的问题
    Go Struct相关问题
    基础数据层相关中间件
    MySql相关问题
    Github
    go windows交叉编译
  • 原文地址:https://www.cnblogs.com/daxiong225/p/4588094.html
Copyright © 2020-2023  润新知