use*_*657 5 java string-comparison
将从控制台输入获取的字符串与数组中的字符串进行比较时,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");
Run Code Online (Sandbox Code Playgroud)
这是删除方法:
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;
}
Run Code Online (Sandbox Code Playgroud)
这是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;
}
Run Code Online (Sandbox Code Playgroud)
将if (target.equals(list[scan]))始终返回false,除非我将其更改为if (target.toString().equals(list[scan].toString()).
我使用an ArrayList来表示列表的数组实现.列表的前面保留在数组索引0处.如果有帮助,则扩展此类以创建特定类型的列表.如果需要,我可以发布所有课程.
如果myNameList有一个String泛型参数,那么这将不起作用,因为 noString将等于 的类型MyOrderedList。
如果myNameList有MyOrderedList通用参数,那么您需要确保为其定义一个equals()方法。
| 归档时间: |
|
| 查看次数: |
5536 次 |
| 最近记录: |