简体   繁体   English

使用 LinkedList 和 ListIterator 按字母顺序返回元素

[英]Using a LinkedList And ListIterator to return elements in alphabetical order

The function 'addInOrder' is supposed to add String elements (names of Australian cities) in alphabetical order to a LinkedList 'placesToVisit'.函数 'addInOrder' 应该按字母顺序将字符串元素(澳大利亚城市的名称)添加到 LinkedList 'placesToVisit'。

And according to the tutorial I was following, 'addInOrder' function actually worked as intended.根据我遵循的教程,“addInOrder”函数实际上按预期工作。 However, the function was written in a way to return a boolean, which is private static boolean addInOrder(LinkedList<String> linkedList, String newCity) {} .但是,该函数是以返回布尔值的方式编写的,它是private static boolean addInOrder(LinkedList<String> linkedList, String newCity) {}

But I wanted to experiment and decided to write the function 'addInOrder' to return void instead, which is private static void addInOrder(LinkedList<String> linkedList, String newCity) {} .但我想尝试并决定编写函数 'addInOrder' 来返回 void ,它是private static void addInOrder(LinkedList<String> linkedList, String newCity) {}

But the output did not return in alphabetical order and there were even duplicates despite the use of 'break' keyword in the while loop.但是输出没有按字母顺序返回,尽管在 while 循环中使用了 'break' 关键字,甚至还有重复。

Original code according to the tutorial was:根据教程的原始代码是:

   private static boolean addInOrder(LinkedList<String> linkedList, String newCity) {
    ListIterator<String> stringListIterator = linkedList.listIterator();

        while (stringListIterator.hasNext()) {
            int comparison = stringListIterator.next().compareTo(newCity);
            if (comparison == 0) {
                System.out.println(newCity + " already listed as destination.");
                return false;
            } else if (comparison > 0) {
                stringListIterator.previous();
                stringListIterator.add(newCity);
                return true;
            }
        }
        stringListIterator.add(newCity);
        return true;
     }

Output:输出:

Now visiting, Adelaide
Now visiting, Brisbane
Now visiting, Canberra
Now visiting, Darwin
Now visiting, Melbourne
Now visiting, Perth
Now visiting, Sydney

My code:我的代码:

public class Demo {
public static void main(String[] args) {
    LinkedList<String> placesToVisit = new LinkedList<>();
    addInOrder(placesToVisit, "Sydney");
    addInOrder(placesToVisit, "Melbourne");
    addInOrder(placesToVisit, "Brisbane");
    addInOrder(placesToVisit, "Perth");
    addInOrder(placesToVisit, "Canberra");
    addInOrder(placesToVisit, "Adelaide");
    addInOrder(placesToVisit, "Darwin");

    printList(placesToVisit);
}

private static void printList(LinkedList<String> linkedList) {
    Iterator<String> i = linkedList.iterator();

    while (i.hasNext()) {
        System.out.println("Now visiting, " + i.next());
    }

    System.out.println("=============================");
}

private static void addInOrder(LinkedList<String> linkedList, String newCity) {
    ListIterator<String> stringListIterator = linkedList.listIterator();

    if (linkedList.size() == 0) {
        linkedList.add(newCity);
    } else {
        while (stringListIterator.hasNext()) {
            int comparison = stringListIterator.next().compareTo(newCity);
            if (comparison == 0) {
                System.out.println(newCity + " already listed as destination.");
                break;
            } else if (comparison > 0) {
                stringListIterator.previous();
                stringListIterator.add(newCity);
                break;
            } else if (comparison < 0) {
                stringListIterator.add(newCity);
                break;
            }
        }
        linkedList.addLast(newCity);
    }

}
} 

Output:输出:

Now visiting, Adelaide
Now visiting, Darwin
Now visiting, Brisbane
Now visiting, Canberra
Now visiting, Perth
Now visiting, Melbourne
Now visiting, Sydney
Now visiting, Melbourne
Now visiting, Brisbane
Now visiting, Perth
Now visiting, Canberra
Now visiting, Adelaide
Now visiting, Darwin

You are adding each city twice.您将每个城市添加两次。 First you are adding it in the loop just before break .首先,您在break之前将它添加到循环中。 Then you are adding it at the end of the list after the loop, in this line:然后将它添加到循环后列表的末尾,在这一行中:

    linkedList.addLast(newCity);

You will also notice that the last half of your output is exactly your cities in the order you inserted them.您还会注意到,输出的后半部分正是您插入城市的顺序。

break is weaker than return . breakreturn弱。 break continues execution after the loop while return exits the method completely. break在循环后继续执行,而return完全退出该方法。

Edit: You've got one further problem: you are not adding in order.编辑:您还有一个问题:您没有按顺序添加。 If the list is non-empty, your if / else chain will always find one true case.如果列表非空,则您的if / else链将始终找到一个真实案例。 This means that unless the city to be added is already first in the list(!), you will add it either before or after the first element, no later.这意味着除非要添加的城市已经是列表中的第一个(!),否则您将在第一个元素之前或之后添加它,而不是稍后。

  1. Sydney comes into an empty list.悉尼进入一个空列表。 As the only city it is only added once.作为唯一的城市,它只添加一次。
  2. Melbourne is added before Sydney (correct) and at the end (incorrect).在悉尼(正确)和最后(不正确)添加墨尔本。
  3. Brisbane is added before Melbourne and at the end.在墨尔本之前和最后添加布里斯班。
  4. Perth is added after Brisbane (incorrect) and at the end (also incorrect)珀斯加在布里斯班之后(不正确)和最后(也不正确)
  5. Canberra is added after Brisbane and at the end.堪培拉是在布里斯班之后和最后加入的。
  6. Adelaide is added before Brisbane and at the end.阿德莱德添加在布里斯班之前和末尾。
  7. Darwin is added after Adelaide and at the end.达尔文是在阿德莱德之后和最后添加的。

As an aside, for production code I would prefer to use ArrayList rather than LinkedList . ArrayListLinkedList ,对于生产代码,我更喜欢使用ArrayList而不是LinkedList If there were 100 000 cities insertion in order into the ArrayList might become prohibitively expensive.如果有 100 000 个城市按顺序插入ArrayList可能会变得非常昂贵。 If so, I would just insert at the end and sort the list after all cities had been added.如果是这样,我只会在最后插入并在添加所有城市后对列表进行排序。

After corrections posted by the contributor (Ole VV) : "break is weaker than return. break continues execution after the loop while return exits the method completely."在贡献者 (Ole VV) 发布更正后:“break 比 return 弱。break 在循环后继续执行,而 return 完全退出方法。”

I reviewed the code:我查看了代码:

private static void addInOrder(LinkedList<String> linkedList, String newCity) {
    ListIterator<String> stringListIterator = linkedList.listIterator();

    if (linkedList.size() != 0) {
        while (stringListIterator.hasNext()) {
            int comparison = stringListIterator.next().compareTo(newCity);
            if (comparison == 0) {
                System.out.println(newCity + " already listed as destination.");
                return; //return keyword is used instead of break keyword to exit the method
            } else if (comparison > 0) {
                stringListIterator.previous();
                stringListIterator.add(newCity);
                return; //return keyword is used instead of break keyword to exit the method
            }
        }
    }
    stringListIterator.add(newCity);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM