对象进行比较

package lxd;

public class LxdT {

    public static void main(String[] args) {
        Per p1 = new Per("张三", 17, "男");
        Per p2 = new Per("张三", 18, "男");

        boolean b = p1.compare(p2);  
        System.out.println(b);

    }

}

class Per {
    private String name;
    private int age;
    private String sex;

    public Per() {
    }
    //有参构造方法,实例话对象的同时的增加原始属性
    public Per(String name, int age, String sex) {
        this.name = name;
        this.age = age;
        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 getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    // 对象对比,返回值boolean的 方法,参数per类

    public boolean compare(Per per) {
        //传入空置的情况
        if (per == null) {
            return false;
        }
        //与自身比较的情况
        if (this == per) {
            return true;
        }
        //两个对象的属性分别对比
        if (this.getAge() == per.getAge() && this.getName().equals(per.getName())
                && this.getSex().equals(per.getSex())) {
            return true;
        } else {
            return false;
        }
    }

}
原文地址:https://www.cnblogs.com/xiandong/p/7929801.html