其他分享
首页 > 其他分享> > toString、equals、hashCode

toString、equals、hashCode

作者:互联网

1.toString需要进行重写
2.equals用于引用数据类型比较,==用于基本数据类型比较
3.hashCode获取对象的哈希值,代表地址

package com.javastudy.example04;

import java.util.Objects;

public class Test {
    public static void main(String[] args) {
        ToString s1=new ToString();
        String x1=s1.toString();
        System.out.println(x1);
        Equals equals1 = new Equals("hzx",22,"man");
        Equals equals2 = new Equals("hzx",22,"man");
        System.out.println(equals1.equals(equals2));//引用数据类型       true
        System.out.println(equals1==equals2);       //基本数据类型才用== false
        System.out.println(equals1.hashCode());
        System.out.println(equals2.hashCode());
    }

}
class ToString{
    String year="2022";
    int month;
    int day;
    public String toString(){
        return year;
    }
}
class Equals{

    public Equals(String name, int year, String sex) {
        this.name = name;
        this.year = year;
        this.sex = sex;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Equals equals = (Equals) o;
        return year == equals.year &&
                Objects.equals(name, equals.name) &&
                Objects.equals(sex, equals.sex);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, year, sex);
    }

    String name;
    int year;
    String sex;
}

标签:String,sex,equals,Equals,toString,year,hashCode,name
来源: https://www.cnblogs.com/hzxiang/p/16468108.html