Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String comparison using .equals() does not work in Java.

When comparing a string taken from console input to a string inside an array, it is always false unless I add .toString(). Both strings are equal and it should work without adding the .toString(). Can anyone help me figure out why?

Here I get the string I want to compare from the console:

System.out.println("\nEnter the name you wish to remove from the list.");
String name = in.nextLine();
System.out.println("\n\"" + myNameList.remove(new MyOrderedList(name)) + "\"" + " removed from the name list\n");

Here is the remove method:

public T remove(T element) {
    T result;
    int index = find(element);

    if (index == NOT_FOUND) {
        throw new ElementNotFoundException("list");
    }

    result = list[index];
    rear--;

    /** shift the appropriate elements */
    for (int scan = index; scan < rear; scan++) {
        list[scan] = list[scan+1];
    }

    list[rear] = null;
    return result;
}

Here is the find method that is were the problem is:

private int find(T target) {
    int scan = 0, result = NOT_FOUND;
    boolean found = false;

    if (!isEmpty()) {
        while (!found && scan < rear) {
            if (target.equals(list[scan])) { // Not sure why this does not work until I add the .toString()s
                found = true;
            }
            else {
                scan++;
            }
        }
    }

    if (found) {
        result = scan;
    }
    return result;
}

The if (target.equals(list[scan])) always returns false unless I change it to if (target.toString().equals(list[scan].toString()).

I am using an ArrayList to represent an array implementation of a list. The front of the list is kept at array index 0. This class is extended to create a specific kind of list if that helps. I can post all classes if needed.

like image 695
user1677657 Avatar asked Oct 06 '22 14:10

user1677657


2 Answers

You are only using String.equals if the first argument is a String.

String comparison using .equals() does not work java

It appears this is the thing which does work. Its T.equals() which doesn't work.


If you have this working, it means you have overridden toString() sensibly.

target.toString().equals(list[scan].toString()

but if this doesn't work

target.equals(list[scan])

it means you haven't overridden equals(Object) correctly.

like image 134
Peter Lawrey Avatar answered Oct 10 '22 02:10

Peter Lawrey


If myNameList has a String generic parameter, then this will not work, because no String will equal a type of MyOrderedList.

If myNameList has a MyOrderedList generic parameter, then you will need to make sure that you define an equals() method for it.

like image 40
nicholas.hauschild Avatar answered Oct 10 '22 03:10

nicholas.hauschild