#java #iterator
#java #итератор
Вопрос:
Я включил много операторов SoP, просто чтобы посмотреть, что происходит в коде.
Когда эта строка
addInOrder(placesToVisit, "Sydney");
выполняется, while
цикл в addInOrder()
методе не будет выполнен, потому что в LinkedList
и hasNext()
не будет элемента, возвращающего false, «Sydney» будет вставлен в индекс 0.
Теперь, когда
addInOrder(placesToVisit, "Melbourne");
выполняется, элемент управления войдет в while
цикл в addInOrder()
методе. Поскольку «Melbourne» должен быть вставлен перед «Sydney», чтобы получить список в лексиографическом порядке, compareTo()
вернет значение > 0. Теперь в этом блоке мы использовали previous()
метод для перемещения курсора перед «Sydney (index = 0)», но перед индексом 0 его значение равно нулю или -1, также я напечатал previousIndex()
значение, равное -1, все еще оно работает.
Вот результат:
nextIndex: 0
previousIndex: -1
Это напечатано перед переходом в цикл while
Now visiting Sydney
=============================
nextIndex: 0
previousIndex: -1
nextIndex: 0
nextIndex: 1
Здесь nextIndex = 1, это означает, currentIndex = 0, как может предыдущий индекс также равен 0;
previousIndex: 0
counter 1
6
comparision > 0
nextIndex: 1
previousIndex() 0
Здесь nextIndex = 1, это означает, currentIndex = 0, тогда как предыдущий индекс может быть также 0? Должно быть -1
Now visiting Melbourne
Now visiting Sydney
=============================
Now visiting Melbourne
Now visiting Sydney
=============================
Пожалуйста, объясните, почему это работает. Когда мы используем previous() для индекса 0 и пытаемся что-то вставить, это должно выдать какую-то ошибку или что-то в этом роде. Не так ли?
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;
}
}
Комментарии:
1. Почему вы не используете
Queue<T>
для этой цели?
Ответ №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