【问题标题】:Shouldn't it give some error coz we are trying to access the previous index using previous() when we have only one element in the LinkedList当我们在 LinkedList 中只有一个元素时,它不应该给出一些错误,因为我们试图使用 previous() 访问前一个索引
【发布时间】:2020-09-08 09:41:21
【问题描述】:

我已经包含了许多 SoP 语句,只是为了看看代码中发生了什么。

当这条线

addInOrder(placesToVisit, "Sydney");

执行后,addInOrder() 方法中的while 循环将不会执行,因为LinkedListhasNext() 中没有元素将返回false,“Sydney”将插入索引0。

现在

addInOrder(placesToVisit, "Melbourne");

执行后,控件将进入addInOrder()方法中的while循环。由于必须在“Sydney”之前插入“Melbourne”才能按 Lexographical 顺序获取列表,compareTo() 将返回一个 > 0 的值。现在在这个块中,我们使用了previous() 方法将光标移动到“Sydney”之前(index = 0)",但在索引 0 之前,它的 null 或 -1,我也打印了 -1 的 previousIndex() 值,它仍然在工作。

这是输出:

nextIndex: 0
previousIndex: -1

这是在进入 while 循环之前打印出来的

Now visiting Sydney
=============================
nextIndex: 0
previousIndex: -1
nextIndex: 0
nextIndex: 1

这里的nextIndex = 1,也就是说currentIndex = 0,怎么可能previousIndex也为0;

previousIndex: 0
counter 1
6
comparision > 0
nextIndex: 1
previousIndex() 0

这里nextIndex = 1,也就是说currentIndex = 0,那previousIndex怎么可能也是0呢?应该是 -1

Now visiting Melbourne
Now visiting Sydney
=============================
Now visiting Melbourne
Now visiting Sydney
=============================

请解释为什么它有效。当我们在索引 0 上使用 previous() 并尝试插入一些东西时,它应该会给出一些错误或其他东西。不是吗?

public class Launch {

    static int counter;
    public static void main(String[] args) {
        LinkedList<String> placesToVisit = new LinkedList<String>();
            
        addInOrder(placesToVisit, "Sydney");
        printList(placesToVisit);
        addInOrder(placesToVisit, "Melbourne");
        printList(placesToVisit);

        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 boolean addInOrder(LinkedList<String> linkedList, String newCity)
    {
        
        ListIterator<String> stringListIterator = linkedList.listIterator();
        System.out.println("nextIndex: " + stringListIterator.nextIndex());
        System.out.println("previousIndex: " + stringListIterator.previousIndex());
        
        while(stringListIterator.hasNext())
        {
            System.out.println("nextIndex: " + stringListIterator.nextIndex());
            
            int comparison = stringListIterator.next().compareTo(newCity);
            
            System.out.println("nextIndex: " + stringListIterator.nextIndex());
            System.out.println("Here nextIndex = 1, that means, currentIndex = 0, then how can be the previousIndex also 0 ? Is should be -1");
            System.out.println("previousIndex: " + stringListIterator.previousIndex());
                        
            counter++;
            System.out.println("counter "+ +counter);
            System.out.println(comparison);
            if(comparison == 0)
            {
                // equal, do not add
                System.out.println(newCity + " is already in the list. So discarded.");
                System.out.println("comarision = 0");
                System.out.println();
                return false;
            }
            else if(comparison > 0)
            {
                //move control to previous position and add the new item
                System.out.println("comarision > 0");
                System.out.println("nextIndex: " + stringListIterator.nextIndex());
                System.out.println("previousIndex() "+stringListIterator.previousIndex());
                System.out.println("Here nextIndex = 1, that means, currentIndex = 0, then how can be the previousIndex also 0 ? Is should be -1");
                stringListIterator.previous();
                stringListIterator.add(newCity);
                System.out.println();
                return true; 
            }
            else if(comparison < 0)
            {
                // Do nothing, let it go ahead
                System.out.println("comarision < 0");
                System.out.println();
            }
        }
        stringListIterator.add(newCity);
        System.out.println("This printed before going into while loop");
        return true;
    }
}

【问题讨论】:

  • 你为什么不使用Queue&lt;T&gt;来达到这个目的?

标签: java iterator


【解决方案1】:
When we use previous() on index 0 and try to insert something, it should give some error or something.

我们知道在链表的概念中,指针是指向链表中一个节点或元素的东西。

但在迭代器中有游标的概念,与指针不同,它存在于节点/元素之间。

这里,

nextIndex() : 给出光标的下一个索引值。

previousIndex():给出游标的宝贵索引值。

在你的情况下;

当 nextIndex:0 和 previousIndex:-1 时,光标就在索引 0 之前。 当 nextIndex:1 和 previousIndex:0 时,光标在第一个和第二个元素之间..

对其他人也是如此..

不要混淆游标和指针。

例子:

  List<String> list = new ArrayList<>();
list.add("Berlin");
list.add("Sydney");
list.add("London");
list.add("Italy");

// Get the list iterator
ListIterator<String> iterator = list.listIterator();


while (iterator.hasNext()) {
  int ii = iterator.previousIndex();
  int index = iterator.nextIndex();
  String element = iterator.next();
  System.out.println("PreviousIndex="+ii+", NextIndex=" + index + ", Element=" + element);
}

输出:

PreviousIndex=-1, NextIndex=0, Element=Berlin
PreviousIndex=0, NextIndex=1, Element=Sydney
PreviousIndex=1, NextIndex=2, Element=London
PreviousIndex=2, NextIndex=3, Element=Italy

【讨论】:

    最近更新 更多