Java:值是相同的但是如果声明要检查它们是否相等则不会起作用?

时间:2015-05-30 04:24:16

标签: java if-statement

我试图查看两个Song()对象是否相同,最终会抛出一个重复的歌曲条目Exception,但我遇到了一些麻烦。用于检查它们是否相等的if语句不希望将它们视为相等。我让控制台在每个歌曲条目上打印他们的值作为测试,他们打印相同,但if语句没有初始化。 这是我的代码:

case 1: //ENTER A SONG TO DATABASE

    try {
        Song newSong = enterSong();
        int logSize = database.getLogicalSize();
        if (logSize>0){
            System.out.println(newSong.getName() + " " + database.getSongName(0));
            if (newSong == database.getSong(0)){
                throw new Exception("Exception: duplicate song entry!");
            }
        }
        database.addSong(newSong);
    }
    catch (Exception e){
        System.out.println(e.getMessage());
    }

break;

2 个答案:

答案 0 :(得分:0)

if (newSong.equals(database.getSong(0))){
               throw new Exception("Exception: duplicate song entry!");

来自Oracle Doc:

" public boolean equals(Object obj)

指示某个其他对象是否等于"这个。

equals方法在非null对象引用上实现等价关系:

It is reflexive: for any non-null reference value x, x.equals(x) should return true.
It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
For any non-null reference value x, x.equals(null) should return false. 

类Object的equals方法实现了对象上最具辨别力的等价关系;也就是说,对于任何非空引用值x和y,当且仅当x和y引用同一对象时,此方法才返回true(x == y的值为true)。

请注意,通常需要在重写此方法时覆盖hashCode方法,以便维护hashCode方法的常规协定,该方法声明相等的对象必须具有相同的哈希代码。

参数:     obj - 要与之比较的参考对象。 返回:     如果此对象与obj参数相同,则返回true;否则返回false。否则为假。"

答案 1 :(得分:0)

<file1_line_content, file2_line_contents>适用于基本类型,例如==int,...如果要比较非基本类型的对象,则必须覆盖long方法。等于可以像这样覆盖:

equals

你可以在你的函数中使用它:

@Override
public boolean equals(Object sng) {
   if (!(sng instanceof Song))
        return false;
    if (sng == this)
        return true;

    Song otherSong = (Song) sng ;

    //check your equality between this two here.
}