Java: Is there a way to effectively insert or remove many of the middle elements of a…

I was expecting to find this in Java’s LinkedList, since the point of linked lists is to be able to efficiently insert (and remove) anywhere (assuming you have some kind of pointer to the location where you want to insert or remove). I’m not finding anything in the API though. Am I overlooking something?

The closest thing I can find to this are the add and remove method in ListIterator. This has some limitations though. In particular, other iterators become invalid as soon as the underlying LinkedList is modified via remove, according to the API. This is born out in my tests as well; the following program results in a IllegalStateException:

import java.util.*;
public class RemoveFromLinkedList {
    public static void main(String[] args) {
        LinkedList myList= new LinkedList();
        for (int i = 0; i < 10; ++i) {
            myList.add(i);
        }

        ListIterator i1 = myList.listIterator();
        ListIterator i2 = myList.listIterator();
        for (int i = 0; i < 3; ++i) {
            i1.next();
            i2.next();
        }

        System.out.println("i1.next() should be 3: " + i1.next());
        i1.remove();
        i1.remove();

        // Exception!
        System.out.println("i2.next() should be 5: " + i2.next());
    }
}

Ideally, what I’m expecting is something like this:

// In my imagination only. This is the way Java actually works, afaict.

// Construct two insertion/deletion points in LinkedList myLinkedList.
myIterator = myLinkedList.iterator();
for (...) {
 myIterator.next();
}
start = myIterator.clone();
for (...) {
 myIterator.next();
}

// Later...

after = myLinkedList.spliceAfter(myIterator, someOtherLinkedList);
// start, myIterator, and after are still all valid; thus, I can do this:
// Removes everything I just spliced in, as well as some other stuff before that.
myLinkedList.remove(start, after);
// Now, myIterator is invalid, but not start, nor after.

C++ has something like this for its list
class (template). Only iterators pointing to moved elements become invalidated, not ALL iterators.

With java.util.LinkedList, the only way to refer to locations in the list for later efficient manipulation is an Iterator, and Iterators are invalidated if the underlying list is modified by something other than this Iterator.

If you really need that capability, you’ll have to look beyond the Java API, or write it yourself.

Hello, buddy!责编内容来自:Hello, buddy! (源链) | 更多关于

阅读提示:酷辣虫无法对本内容的真实性提供任何保证,请自行验证并承担相关的风险与后果!
本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合编程 » Java&colon; Is there a way to effectively insert or remove many of the middle elements of a…

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录