2016-11-07 56 views
2

我用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()); 
    } 
} 
+2

你可以包括你運行的實際代碼來得出這些結論嗎? –

+0

對不起,在這裏。 – Agyss

+0

第二次調用下一個(2)時,它會將光標移動到3,所以前一個將是2.看起來合乎邏輯。 –

回答

5

它想象中的Java迭代器永遠指向特定元素是有用的,但無論是第一個元素之前,兩個元素或只是間中在最後一個元素之後。

因此,迭代器創建時,它看起來像

1 2 3 4 
^ 

當你調用next1返回和迭代器向前移動:

1 2 3 4 
^ 

當你再打電話next,返回2和迭代器向前移動:

1 2 3 4 
    ^

當你調用prev2返回和迭代器向後移動:

1 2 3 4 
^ 

所以要next的下一次調用將返回2

請注意,現在有方法可以獲取迭代器的「當前」值。獲得值的唯一方法是移動迭代器。

實現迭代器的另一種方式,我們可以在C++中看到。要使用C++迭代器,我們需要三個單獨的操作:檢索當前值,檢查是否有移動值來檢索和移動迭代器。雖然java方法只需要兩個操作:檢查是否有移動值來檢索和獲取值和移動迭代器。因此,在Java中實現自定義迭代器比在C++中更簡單。

+0

確實是一個很好的補充,至少它使它更容易成像。但他們爲什麼這樣做?只要它可以更直觀,爲什麼不這樣做呢? – Agyss

+0

增加了理由。 – kgeorgiy