代码之家  ›  专栏  ›  技术社区  ›  YungSaucer406

如果数组列表中有重复项,为什么我的代码有时不返回true?

  •  0
  • YungSaucer406  · 技术社区  · 2 年前

    我正在写一个编码任务,其中我得到了一个x个生日的列表(使用整数来存储日期),如果有重复,我需要返回(只有一个布尔值)。我已经写了一些不同的方法来返回正确的值,有些只是有时有效,我不知道为什么。我希望有人能澄清我做错了什么,或者我用来编码的平台是否有漏洞。谢谢你的帮助!

    birthdays = merge(birthdays);//this is a merge sort that sorts the ArrayList(it does actually work)
    for(int i = 0; i<birthdays.size()-1; i++)
        {
        if(birthdays.get(i) == birthdays.get(i+1))
            {
                return true;
            }
        }
    return false;
    
    1 回复  |  直到 2 年前
        1
  •  1
  •   ControlAltDel    2 年前

    Java中的==运算符仅测试主键(int、chars等)之间的相等性

    因此,您应该更改这一行:

        if(birthdays.get(i) == birthdays.get(i+1))
    

    对此:

        if(birthdays.get(i).equals(birthdays.get(i+1)))