【发布时间】:2020-09-21 16:59:10
【问题描述】:
我的一个程序中有以下方法:
/**
* Returns the index of the first occurrence of the specified item.
* If the specified item in not part of the list
* the method indexOf returns -1
*
* @param item
* @return index of the first occurrence of the item; -1 if the word was not found.
*/
public int indexOf(String item) {
int index = 0;
//While we haven't reached the end of the list
while(head != null) {
//If the items are equal return true
if(head.item == item) {
return index;
}
//Set the head to the next and increment the index
head = head.next;
index++;
}
return -1;
}
虽然对我来说一切看起来都是正确的(除了需要将 head.item == item 更改为 head.item.equals(item)),但它并没有给我正确的索引。
虽然它确实给了我 -1 的元素,但每次它返回 0 作为列表中元素的索引时,我都无法弄清楚为什么索引是不递增。
任何意见将不胜感激!谢谢
【问题讨论】:
-
这能回答你的问题吗? How do I compare strings in Java?
-
head在哪里初始化?如果您第二次拨打indexOf,head是否仍然是上次拨打电话后的null? -
我得到了一个部分开始的 WordList 类型(字符串列表)。唯一的字段是头节点、尾节点和 int n(列表中的单词数)。该列表是在 main 方法中通过简单地将字符串附加到列表中来创建的(append 方法也已经为我编写了)。
-
此外,append 方法肯定会追加到列表的末尾。我无法弄清楚这里出了什么问题。
-
你能展示更多你的类定义吗?我想查看
class行本身和实例变量(如head和tail)。不过,您不需要包含其他功能。
标签: java list linked-list increment