当比较从控制台输入获取的字符串与数组中的字符串时,false
除非我添加.toString()
. 两个字符串是相等的,它应该可以在不添加.toString()
. 谁能帮我弄清楚为什么?
在这里,我得到了我想从控制台比较的字符串:
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");
这是删除方法:
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())
我使用 anArrayList
来表示列表的数组实现。列表的前面保留在数组索引 0 处。如果有帮助,可以扩展此类以创建特定类型的列表。如果需要,我可以发布所有课程。