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

问题描述 投票:0回答:1

我正在编写一个编码作业,其中给出了 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;
java duplicates
1个回答
0
投票

Java 中的 == 运算符仅测试基元(整数、字符等)之间的相等性

因此您应该更改此行:

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

对此:

    if(birthdays.get(i).equals(birthdays.get(i+1)))
© www.soinside.com 2019 - 2024. All rights reserved.