我用java.util.ListIterator中在java.util.LinkedList中的工作期待它像工作,在這個僞代碼:的Java的LinkedList的ListIterator行爲
list = (1,2,3,4)
iterator.next should be 1
iterator.next should be 2
iterator.prev should be 1
iterator.next should be 2
但順序是這樣的:
iterator.next is 1
iterator.next is 2
iterator.prev is 2
iterator.next is 2
我不敢相信這是它的工作方式,所以我創建了一個測試,但它產生相同的輸出。 所以我在的ListIterator的定義當然是仔細一看:
next()
Returns the next element in the list and advances the cursor position.
previous()
Returns the previous element in the list and moves the cursor position backwards.
所以執行是正確的,但我仍然與他們爲什麼選擇了這種行爲的問題?我不會以更直接的方式獲得它嗎?
下面是測試代碼:
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import java.util.LinkedList;
import java.util.ListIterator;
public class LinkedListTest {
ListIterator<Integer> iterator;
@Before
public void setUp() throws Exception {
LinkedList<Integer> list = new LinkedList<>();
for (int i = 1; i < 5; i++) {
list.add(i);
}
iterator = list.listIterator();
}
@Test
public void successfullTest() throws Exception
{
assertEquals(1, (int) iterator.next());
assertEquals(2, (int) iterator.next());
assertEquals(2, (int) iterator.previous());
assertEquals(2, (int) iterator.next());
assertEquals(3, (int) iterator.next());
assertEquals(4, (int) iterator.next());
}
@Test
public void failingTest() throws Exception
{
assertEquals(1, (int) iterator.next());
assertEquals(2, (int) iterator.next());
assertEquals(1, (int) iterator.previous());
assertEquals(2, (int) iterator.next());
assertEquals(3, (int) iterator.next());
assertEquals(4, (int) iterator.next());
}
}
你可以包括你運行的實際代碼來得出這些結論嗎? –
對不起,在這裏。 – Agyss
第二次調用下一個(2)時,它會將光標移動到3,所以前一個將是2.看起來合乎邏輯。 –