2012-12-03 36 views
0

我为玩具编程语言构建一个图形着色分配器。在生成溢出代码时,有时我必须在当前指令之前插入一个负载{用于恢复}或在当前指令{溢出}之后插入。我的代码被表示为对于每个基本块的节点和块内的指令的列表的图,java使用listIterator插入元素

我生成图形节点的DFS有序列表和为每个节点i搜索节点内的指令列表, 使用codeList.listIterator()我可以通过下一个和前一个分别来回和添加插入后插入之前。

插入应该如何使用add()方法在列表的开始处发生?

回答

4

从ListIterator.add API

The element is inserted immediately before the element that would be returned by next(), if any, and after the element that would be returned by previous(), if any. (If the list contains no elements, the new element becomes the sole element on the list.) The new element is inserted before the implicit cursor: a subsequent call to next would be unaffected, and a subsequent call to previous would return the new element. 

这里是它如何工作的实践为例

List<String> l = new ArrayList<String>(); 
    l.add("1"); 
    ListIterator<String> i = l.listIterator(); 
    i.add("2"); 
    while (i.hasPrevious()) { 
     i.previous(); 
    } 
    i.add("3"); 
    System.out.println(l); 

输出

[3, 2, 1] 

,我们可以用的ListIterator

做更多的花样
+0

@ jahroy“如何插入使用add()方法在列表的开头?”不,这正是他想要的。如果他尝试在旧的迭代器上调用next或previous,则使用新的迭代器将抛出异常('ConcurrentModificationException')。他将不得不修改他的'for'循环或他用来容纳新调用的任何内容,以便在他调用'add'时未调用'next'。 – Brian

+0

@jahroy你走了。这个答案是正确的。也许Evgeniy应该在调用add之前显示更多的导航,但完全获得另一个列表工具将无法工作 – Bohemian

+0

@Bohemian已经完成 –