倾月
有你的地方,才是我的家!

在Java之中不仅仅存在两个数字与两个字符串之间的比较,还存在两个对象之间的比较。

众所周知,两个数字之间的比较我们使用“==”,两个字符串之间的比较我们使用“equals()”,那么两个对象之间如何进行比较呢?既然要进行两个对象之间的比较,那么就必须要实现两个对象之间所有属性内容的比较。

下面我们来看一下最为基础的比较方式:

class Shoes{
    private String name;
    private double price;
    public Shoes(){}
    public Shoes(String title, double price){
        this.name = name;
        this.price = price;
    }
    public void setName(String name){
        this.name = name;
    }
    public String getName(){
        return this.name;
    }
    public void setPrice(double price){
        this.price = price;
    }
    public double getPrice(){
        return this.price;
    }
    public String getInfo(){
        return "名称:" + this.name + ",价格:" + this.price;
    }
}
public class ObjectCompare{
    public static void main(String args[]){
        Shoes s1 = new Shoes("ADIDAS", 3980.0);
        Shoes s2 = new Shoes("NIKE", 1789.0);
        if(s1.getName().equals(s2.getName()) && s1.getPrice() == s2.getPrice()){
            System.out.println("是同一个对象!");
        }else{
            System.out.println("不是同一个对象!");
        }
    }
}

运行结果:

由此可以发现,s1与s2两个对象的属性内容明显不一样,故不是同一个对象。若,s1与s2两个对象的属性内容完全一样,则是同一个对象。在此,不再进行测试。

但是,从上述代码中可以发现,此程序存在问题:主方法main()之中的程序逻辑过于复杂。我们写代码的原则就是在main()方法之中最好隐藏所有的细节逻辑,越简单越好!

下面我们来看一下对象比较的实现:

class Shoes{
    private String name;
    private double price;
    public Shoes(){}
    public Shoes(String name, double price){
        this.name = name;
        this.price = price;
    }
    public void setName(String name){
        this.name = name;
    }
    public String getName(){
        return this.name;
    }
    public void setPrice(double price){
        this.price = price;
    }
    public double getPrice(){
        return this.price;
    }
    public boolean compare(Shoes sh){
        if(sh == null){
            return false;
        }
        if(this == sh){
            return true;
        }
        if(this.getName().equals(sh.getName()) && this.getPrice() == sh.getPrice()){
            return true;
        }else{
            return false;
        }
    }
    public String getInfo(){
        return "名称:" + this.name + ",价格:" + this.price;
    }
}
public class ObjectCompare{
    public static void main(String args[]){
        Shoes s1 = new Shoes("ADIDAS", 3980.0);
        Shoes s2 = new Shoes("NIKE", 1789.0);
        if(s1.compare(s2)){
            System.out.println("是同一个对象!");
        }else{
            System.out.println("不是同一个对象!");
        }
    }
}

运行结果:

在这里,大家需要注意一点的是,在进行对象比较的时候,一定要判断是否为null、内存地址是否相同、属性是否相同!

至此,Java之中的对象比较讲解完毕,欢迎大家进行评论,谢谢!

posted on 2019-02-26 10:57  Holson  阅读(6733)  评论(0编辑  收藏  举报