java使用listIterator插入元素

java使用listIterator插入元素,java,arraylist,iterator,listiterator,Java,Arraylist,Iterator,Listiterator,我正在为一种玩具编程语言构建一个图形着色分配器。在生成溢出代码时,有时我必须在当前指令之前插入一个load{for restoring}或在当前指令之后插入一个insert{for spill}。我的代码表示为一个图形,每个基本块有一个节点,块内有一个指令列表 我生成图节点的dfs有序列表,并为每个节点遍历节点内的指令列表, 使用codeList.listIterator()我可以分别通过next和previous来回,并对insert after和insert before进行添加 如何使用a

我正在为一种玩具编程语言构建一个图形着色分配器。在生成溢出代码时,有时我必须在当前指令之前插入一个load{for restoring}或在当前指令之后插入一个insert{for spill}。我的代码表示为一个图形,每个基本块有一个节点,块内有一个指令列表

我生成图节点的dfs有序列表,并为每个节点遍历节点内的指令列表, 使用codeList.listIterator()我可以分别通过next和previous来回,并对insert after和insert before进行添加


如何使用add()方法在列表的开头插入?

来自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);

我们还可以使用ListIterator.addAPI中的ListIterator实现更多技巧

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);

我们可以用ListIterator做更多的技巧“如何使用add()方法在列表的开头插入?”不,这正是他想要的。如果使用新迭代器试图调用旧迭代器上的
next
previous
,则使用新迭代器将抛出异常(
ConcurrentModificationException
)。他必须修改他的
循环或他正在使用的任何东西,以适应新的调用,这样当他调用
add
@jahroy时,就不会调用
next
。这个答案是正确的。也许Evgeniy在调用add之前应该显示更多的导航,但是完全获得另一个listiterator是行不通的,请考虑一下我的列表只有1。我使用列表迭代器执行下一步,现在光标将隐式指向1之后,我的“nextval”将指向1,如果我执行hasprevious()检查,然后执行previous,那么我的光标将指向1之前,而“prevval”将指向1。(可能是一个普通的最后一个val指针!)那么现在插入发生在开始处?我的直觉就在这里吗?理解它的最好方法就是用它来做实验。只需将您的场景放在几行代码中并运行即可。@jahroy“如何使用add()方法在列表的开头插入内容?”不,这正是他想要的。如果使用新迭代器试图调用旧迭代器上的
next
previous
,则使用新迭代器将抛出异常(
ConcurrentModificationException
)。他必须修改他的
循环或他正在使用的任何东西,以适应新的调用,这样当他调用
add
@jahroy时,就不会调用
next
。这个答案是正确的。也许Evgeniy在调用add之前应该显示更多的导航,但是完全获得另一个listiterator是行不通的,请考虑一下我的列表只有1。我使用列表迭代器执行下一步,现在光标将隐式指向1之后,我的“nextval”将指向1,如果我执行hasprevious()检查,然后执行previous,那么我的光标将指向1之前,而“prevval”将指向1。(可能是一个普通的最后一个val指针!)那么现在插入发生在开始处?我的直觉就在这里吗?理解它的最好方法就是用它来做实验。只需将您的场景放在几行代码中并运行它。