将控制台输入的字符串与数组中的字符串进行比较时,除非添加.toString()
,否则始终为false
。两个字符串都是相同的,它应该在不添加.toString()
的情况下工作。任何人都可以帮我弄清楚为什么?使用.equals()的字符串比较在Java中不起作用。
在这里,我得到了我想要从控制台来比较字符串:
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");
这里是remove方法:
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;
}
这里是人的问题,查找方法是:
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]))
总是返回false
除非我将其更改为if (target.toString().equals(list[scan].toString())
。
我正在使用ArrayList
来表示一个列表的数组实现。列表的前面保存在索引为0的数组中。如果有帮助,此类将扩展为创建特定种类的列表。如有需要,我可以发布所有课程。
'list'的定义在哪里? –
我认为这是由于泛型 - 看看'目标'变量 - 它真的是字符串的实例吗?尝试实现自己的equals()并跟踪它... – shmoula
不要以为你不能使用它,它已经坏掉了。如果String上的.equals()被破坏,那将是众所周知的。 –