Java中对象比较

在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之中的对象比较讲解完毕,欢迎大家进行评论,谢谢!

转载于:https://www.cnblogs.com/holson/p/10435951.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值