Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading