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.
list?