When comparing a string taken from console input to a string inside an array, it is always false unless I add .toString() . Both lines are equal and they should work without adding .toString() . Can someone help me understand why?
Here I get the line that I want to compare with 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 removal method:
public T remove(T element) { T result; int index = find(element); if (index == NOT_FOUND) { throw new ElementNotFoundException("list"); } result = list[index]; rear--; for (int scan = index; scan < rear; scan++) { list[scan] = list[scan+1]; } list[rear] = null; return result; }
Here is the search method that was the problem:
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; }
if (target.equals(list[scan])) always returns false unless I change it to if (target.toString().equals(list[scan].toString()) .
I use ArrayList to represent an implementation of a list array. The front of the list is stored in the index of array 0. This class is extended to create a specific type of list, if that helps. I can publish all classes if necessary.
source share