【问题标题】:Java what is the use of the equals(Object o) functionJava的equals(Object o)函数有什么用
【发布时间】:2017-04-13 05:23:45
【问题描述】:
public class TVSet {
private String brand;
private double price;
public TVSet()
{
    brand = "";
    price = 0.0;
}
public String getbrand()
{
    return this.brand;
}
public double getprice()
{
    return this.price;
}
public void setbrand(String brand)
{
    if(brand!=null)
    {
        this.brand = brand;
    }
    else
    {
        System.out.println("INVAILD VALUE");
    }
}
public void setprice(double price)
{
    if(price>=0)
    {
        this.price = price;
    }
    else
    {
        System.out.println("INVALID VALUE");
    }
}
public void TVSet(String brand, double price)
{
    if(brand!=null)
    {
        this.brand= brand;
    }
    else
    {
        System.out.println("INVALID VALUE");
    }
    if(price>=0.0)
    {
        this.price = price;
    }
    else
    {
        System.out.println("INVALID VALUE");
    }
}
    @Override
    public String toString()
    {
        //double temp = this.getprice();
        //DecimalFormat f = new DecimalFormat("##,00");
        //String price2 = f.format(temp);
        return String.format("%s, %.2f", brand, price);
    }
    @Override
    public boolean equals(Object o)
    {
        if(o instanceof TVSet)
        {
        TVSet t =(TVSet)o;
        if(price == t.price && brand == t.brand)
        return true;
        }
        return false;
    }
}

这是我的学校作业,告诉我们写一个封装电视机概念的类,假设电视机具有以下属性:品牌(可空字符串,默认为空)和价格(a非负十进制数,默认为 0)。请遵循命名约定来开发课程,包括 - 默认构造函数 - 以品牌和价格为参数的构造函数 - 访问器方法和修改器方法 - toString 方法返回由 (1) 品牌 (2) 逗号和 (3) 价格组成的字符串(四舍五入到小数点后第二位) - 等于方法 - 每当提供无效值时,将一行错误消息“INVALID VALUE”打印到标准输出流。 equals(Object o)有什么用?

【问题讨论】:

  • 默认构造函数仅在类不提供时存在。如果它提供任何构造函数,即使是无参数的构造函数,它也不是默认构造函数。您没有遵循方法 TVSet 的命名约定,实际上也没有遵循任何非覆盖方法。
  • 顾名思义,如果两个对象相等则返回true

标签: java function class


【解决方案1】:

在 Java 中,== 运算符在用于对象时,只会通过引用检查两个对象是否相同。在您的情况下,具有相同品牌和价格的两个不同电视对象将不等于 ==

equals 方法的要点是为您提供一种查看两个不同对象是否等价的方法。在您的情况下,如果两台电视的品牌和价格相同,这将导致true 结果。正是这个,而不是==,在许多库中用于检查相等性。

【讨论】:

    【解决方案2】:

    .equals() 方法在非空对象引用上实现等价关系(示例如下)。请参阅this 文章。

    String h = "hello";
    Scanner input = new Scanner(System.in);
    String x = input.next();
    if (h.equals(x)) { //do NOT use ==; this is not used for comparing strings 
    System.out.println("h equals x");
    

    【讨论】:

    • 这个例子与你的代码无关。随机一个简单的例子,帮助大家理解.equals()的用法,对比==
    猜你喜欢
    • 1970-01-01
    • 2015-09-30
    • 2014-09-26
    • 1970-01-01
    • 1970-01-01
    • 2010-12-06
    • 1970-01-01
    • 1970-01-01
    • 2014-01-05
    相关资源
    最近更新 更多