Quantcast
Channel: User Federico klez Culloca - Stack Overflow
Viewing all articles
Browse latest Browse all 485

Answer by Federico klez Culloca for Does the original list decrease in size when I convert a list to a queue and poll?

$
0
0

They may point to the same elements but they're different containers. The Queue is not backed by that list. References to the elements are copied from the list to the queue, but if you remove something from the queue it shouldn't (and doesn't) reflect on the list.

In particular the constructor for LinkedList looks like this

public LinkedList(Collection<? extends E> c) {    this();    addAll(c);}

The addAll method, in turn, look like this (after calling a version of itself and providing the size):

public boolean addAll(int index, Collection<? extends E> c) {    // omitted for brevity    Object[] a = c.toArray();    // omitted for brevity    for (Object o : a) {        @SuppressWarnings("unchecked") E e = (E) o;        Node<E> newNode = new Node<>(pred, e, null);        if (pred == null)            first = newNode;        else            pred.next = newNode;        pred = newNode;    }    // omitted for brevity}

(where first is the first node of the linked list)

So, as you can see, it creates its own nodes. So yeah, if you remove any of those nodes you're not removing anything from the original list.


Viewing all articles
Browse latest Browse all 485

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>