-3

We are working on generics which requires us to have an array of AnyType (the driver implements an array of strings then integers). One of the functions is a boolean function called 'remove' which finds 'x' and removes it, then it returns true. It has no issues finding and removing a string but can't seem to find ints. Why is this?

the code is

public boolean remove(AnyType x)
{
    for(int i = 0; i < length; i++)
    {
        if(arr[i] == x)
        {
            for(int j = i; j < length - 1; j++)
            {
                arr[j] = arr[j + 1];
            }
            length--;
            return true;
        }
    }
    return false;
}
  • 3
    Maybe because you should use `equals` instead of `==`, it will not work with Strings either if you try to `remove(new String("aaa"))` – hoaz Jan 18 '18 at 20:18
  • hoaz was correct, thank you hoaz if you are seeing this – J. A. E. Jan 18 '18 at 20:33

2 Answers2

0

user hoaz's answer fixed the problem. using .equals instead of == was the issue. fixed code looks like this

public boolean remove(AnyType x)
{
    for(int i = 0; i < length; i++)
    {
        if(arr[i].equals(x))
        {
            for(int j = i; j < length - 1; j++)
            {
                arr[j] = arr[j + 1];
            }
            length--;
            return true;
        }
    }
    return false;
}
-1

This question was already solved, but I'd just like to provide additional information.

The reason for this issue was using == to compare rather than .equals. This is a problem because the == equality operator compares based on memory reference, so for example, 1 == 1 is true because 1 is a primitive stored in one place in memory then referenced as needed, whereas two objects would only return true if they were the exact same instance of the object.

.equals, on the other hand, is a method often overridden from Object to compare the object's fields to eachother, and if not overridden, it would fallback to using ==, so it is almost always the preferable method of comparison.

More info: What is the difference between == vs equals() in Java?

Trophonix
  • 82
  • 1
  • 6