我用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.看起来合乎逻辑。 –