将从控制台输入获取的字符串与数组中的字符串进行比较时,除非我添加.toString(),否则它始终为false.两个字符串都相等,它应该在不添加.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;
}
这是find方法,问题是:
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处.如果有帮助,则扩展此类以创建特定类型的列表.如果需要,我可以发布所有课程.
最佳答案
如果myNameList具有String泛型参数,那么这将不起作用,因为没有String将等于MyOrderedList的类型.
原文链接:https://www.f2er.com/java/438188.html如果myNameList具有MyOrderedList泛型参数,那么您需要确保为其定义equals()方法.