Java中的equals与==

15 篇文章 0 订阅

Object类有boolean equals(Object obj)方法,实现为return this == obj。(==用于比较两者地址是否相同,就是两个变量是否引用了同一个对象)

如果子类想要用equals作为内容比较的方法,则要对Object类的boolean equals(Object obj)方法进行Override。

  1. 如果是基本类型比较,那么只能用==来比较,不能用equals,因为equals是对象方法。

    int a=10;
    int b=10;
    a==b;//返回是true
  2. 对于基本类型的包装类型,比如Boolean、Character、Byte、Shot、Integer、Long、Float、Double等的引用变量,==是比较地址的,而equals是比较内容的,因为它们的实现中Override了boolean equals(Object)方法

    String a= new String("abc");
    String b= new String("abc");
    a==b;//结果是false
    a.equals(b);//返回true
  3. 对于自定义的对象类型,需要自己对boolean equals(Object)方法进行Override。下面是标准实现:

    //Written by K@stackoverflow
    public class Main {
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        ArrayList<Person> people = new ArrayList<Person>();
        people.add(new Person("Subash Adhikari",28));
        people.add(new Person("K",28));
        people.add(new Person("StackOverflow",4));
        people.add(new Person("Subash Adhikari",28));
    
        for (int i=0;i<people.size()-1;i++){
            for (int y=i+1;y<=people.size()-1;y++){
                System.out.println("-- " + people.get(i).getName() + " - VS - " + people.get(y).getName());
                boolean check = people.get(i).equals(people.get(y));
                System.out.println(check);
            }
        }
    }
    }
    
    //written by K@stackoverflow
    public class Person {
    private String name;
    private int age;
    
    public Person(String name, int age){
        this.name = name;
        this.age = age;
    }
    
    // 这里
    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (!Person.class.isAssignableFrom(obj.getClass())) {
            return false;
        }
        final Person other = (Person) obj;
        if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
            return false;
        }
        if (this.age != other.age) {
            return false;
        }
        return true;
    }
    
    @Override
    public int hashCode() {
        int hash = 3;
        hash = 53 * hash + (this.name != null ? this.name.hashCode() : 0);
        hash = 53 * hash + this.age;
        return hash;
    }
    
    public int getAge() {
        return age;
    }
    
    public void setAge(int age) {
        this.age = age;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值