Method That Checks For Value in Collection returns false Even When Said Value is Contained in Collection

Viewed 43

I am having an issue with my method below. I am expecting it to compare an inputted parameter against a collection of items. As my code is now it will only return true meaning it will only find the item in the collection if it is of type string, null, or int that is two characters or less. I would like my method to be able to find variables of any type. For example, in my test, I add 0.5 to the collection and pass a parameter of 0.5 to my method. Even though 0.5 is in the collection my method still returns false meaning it can't be found in the collection. I suspect the reason I am not able to find parameters of any type is because of something happing with their type when passing them to the parameter and the collection.

I have been messing around with this code for hours now and still can't figure out what the issue is. If you have any ideas or tips I would love to hear them. Thanks.

My Method:

public boolean contains(Object arg0) {      
//       For loop that searchs are current collection for arg0
        for (Object c : data) {
            if (arg0 == null) {
                System.out.println(arg0 + " value");
                return true;
            } else if (arg0.equals(c)) {
                System.out.println("found " + c + " and " + arg0);
                return true;
            } else {
                System.out.println("couldint find " + arg0);
                return false;
            }
        }

        return false;

Test for method:

@SuppressWarnings("unchecked")
@Test
void testToSortedList() 
{
    ArrayCollection arrayCollection = new ArrayCollection();
    ArrayCollection resultArray = new ArrayCollection();
    // add the objects to the collections

    arrayCollection.add("Test");
    
    resultArray.add(771);
    resultArray.add(.5);

    
    System.out.println(resultArray.addAll(arrayCollection));
    System.out.println(resultArray.contains(771));
    System.out.println(resultArray.contains(.5));
    System.out.println(resultArray.contains("Test"));
}
0 Answers
Related