0

I am trying to do a linear search of a linked list. One search is by int and the other String. What am I doing wrong? **Updated the code based on recommendations.

Within the main

    public static LinkedList<Contributor> contributorList = new LinkedList<>();

        String searchKey = "Jones";
        int intSearchKey = 45;

        System.out.println("Search key " + searchKey + " is found? " + sequentialSearch(contributorList, searchKey));

        System.out.println("Search key " + intSearchKey + " is found? " + sequentialSearch(contributorList, intSearchKey));



Called methods    



    public static <Contributor> boolean sequentialSearch(Iterable<Contributor> contributorList, int intSearchKey) {
    Iterator<Contributor> iter = contributorList.iterator();
    while (iter.hasNext()) {
        if (iter.next().equals(intSearchKey)) {
            return true;
        }
        iter = (Iterator<Contributor>) iter.next();
    }
    return false;
}

public static <Contributor> boolean sequentialSearch(Iterable<Contributor> contributorList, String searchKey) {
    Iterator<Contributor> iter = contributorList.iterator();
    while (iter.hasNext()) {
        if (iter.next().equals(searchKey)) {
            return true;
        }
        iter = (Iterator<Contributor>) iter.next();
    }
    return false;
}
4

2 回答 2

1

看看你在这里的代码:

Iterator<Contributor> iter = contributorList.iterator();
while (iter.hasNext()) {
    if (iter.next().equals(intSearchKey)) {
        return true;
    }
    iter = (Iterator<Contributor>) iter.next();
}

请注意,在第一次调用 时.next(),您期望它返回一个Contributor对象。在第二种情况下,您期望它返回可以转换为Iterator<Contributor>.

我认为您对迭代器在 Java 中的工作方式存在根本性的误解,这就是代码不起作用的原因。迭代器上的.next()方法自动将迭代器向前推进 - 它修改接收器 - 并返回正在迭代的集合中的下一个值。这意味着您不应iter在调用时分配新值.next(),因为您将拥有不兼容的类型。相反,您可能应该像这样构造代码:

Iterator<Contributor> iter = contributorList.iterator();
while (iter.hasNext()) {
    Contributor currElem = iter.next();
    if (currElem.equals(intSearchKey)) {
        return true;
    }
}

请注意,您.next()在循环中只调用一次来获取值,然后在当前循环迭代中使用该值。您永远不会重新分配iter,因为iter在您反复调用时会自动遍历集合.next()

希望这可以帮助!

于 2015-08-03T21:37:42.817 回答
1

此行将 Contributor 对象与 String 进行比较。

if (iter.next().equals(searchKey)) {

没有看到 Contributor 对象,我猜你想要这样的东西

if (iter.next().getKey().equals(searchKey)) {

此外,这条线没有意义:

 iter = (Iterator<Contributor>) iter.next();

iter.next() 返回元素类型,而不是迭代器

于 2015-08-03T21:43:47.500 回答