Search code examples
javaduplicates

Why does my code SOMETIMES not return true if there are duplicates in the Array list?


I am writing a coding assignment where I get given a list of x birthdays(using integers to store day number), and I need to return if there are duplicates(just a boolean value). I have written a few different methods to return the proper value, some only work sometimes, and I don't know why. I was hoping that someone would be able to clarify what I did wrong, or if there is some bug with the platform I am using to code. Thank you for any help!

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;

Solution

  • The == operator in Java only tests for equality between primatives (ints, chars, etc)

    You should therefore change this line:

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

    To this:

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