Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <blockquote> <p>only one who can possibly modify this list is the Constructor of the class holding it </p> </blockquote> <p>In this case you don't need to modify it at all. I suggest you make it always immutable and you won't get this issue.</p> <p>In your constructor you can do</p> <pre><code>List&lt;HierarchyNode&gt; children = new ArrayList&lt;&gt;(); // create/modify collection. this.children = Collections.immutableList(children); </code></pre> <p>This simplifies your method</p> <pre><code>public List&lt;HierarchyNode&gt; getChildren() { return children; } </code></pre> <p>If you make these changes, I suspect you will find where the collection is being modified.</p> <hr> <p>The problem is that <code>Collections.unmodifiableList()</code> prevents modification using the reference returned by this method. It doesn't prevent modification to the collection you are wrapping.</p> <pre><code>List&lt;String&gt; words = new ArrayList&lt;String&gt;(); words.add("hello"); words.add("world"); List&lt;String&gt; unmodifiable = Collections.unmodifiableList(words); List&lt;String&gt; copy = new ArrayList&lt;String&gt;(words); System.out.println("Before modification"); System.out.println("words: " + words); System.out.println("unmodifiable: " + unmodifiable); System.out.println("copy: " + copy); words.remove("hello"); words.add("hi"); System.out.println("\nAfter modification"); System.out.println("words: " + words); System.out.println("unmodifiable: " + unmodifiable); System.out.println("copy: " + copy); </code></pre> <p>prints</p> <pre><code>Before modification words: [hello, world] unmodifiable: [hello, world] copy: [hello, world] After modification words: [world, hi] unmodifiable: [world, hi] copy: [hello, world] </code></pre> <p>The solution without adding a new library, is to copy the collection before returning it.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload