java进阶 equal比较38

package com.cyjt97.eq;
class StuDer{
private String name;
private int age;

public StuDer() {
}

@Override
public boolean equals(Object obj) {
if (obj instanceof StuDer){
StuDer stu = (StuDer) obj;
return this.age == stu.age && this.name.equals(stu.name);
}else {
return false;
}
}

public StuDer(String name, int age) {
this.name = name;
this.age = age;
}

/**
* 获取
* @return name
*/
public String getName() {
return name;
}

/**
* 设置
* @param name
*/
public void setName(String name) {
this.name = name;
}

/**
* 获取
* @return age
*/
public int getAge() {
return age;
}

/**
* 设置
* @param age
*/
public void setAge(int age) {
this.age = age;
}

public String toString() {
return "StuDer{name = " + name + ", age = " + age + "}";
}
}
package com.cyjt97.eq;

public class day01 {
public static void main(String[] args) {
StuDer stu1 = new StuDer("张三",16);
StuDer stu2 = new StuDer("张三",16);

System.out.println(stu1.equals(stu2));
}
}
package com.cyjt97.eq;

import java.util.Objects;

class StuDer {
    private String name;
    private int age;

    public StuDer() {
    }

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

    public StuDer(String name, int age) {
        this.name = name;
        this.age = age;
    }

    /**
     * 获取
     *
     * @return name
     */
    public String getName() {
        return name;
    }

    /**
     * 设置
     *
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * 获取
     *
     * @return age
     */
    public int getAge() {
        return age;
    }

    /**
     * 设置
     *
     * @param age
     */
    public void setAge(int age) {
        this.age = age;
    }

    public String toString() {
        return "StuDer{name = " + name + ", age = " + age + "}";
    }
}

  

  

 

 

posted @ 2023-03-16 16:51  文采呱呱  阅读(8)  评论(0编辑  收藏  举报