Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>Does the second object then replace the first object?</p> </blockquote> <p>No, most developers do explicit checks</p> <pre><code>if(!list.contains(foo)){ list.add(foo); } </code></pre> <blockquote> <p>Also, what happens if two threads try to add those objects exactly at the same time to the ArrayList? Is this even possible? If yes, what happens?</p> </blockquote> <p>Yes, this is possible. If multiple threads write to/read from the same <code>ArrayList</code>, then use the <code>synchronized</code> keyword whenever you access this list</p> <pre><code>public List&lt;Foo&gt; getFoos(){ synchronized(list){ return list; } } public void addFoo(Foo foo){ synchronized(list){ list.add(foo); } } </code></pre> <p><strong>EDIT</strong></p> <p>As someone pointed out, I suppose checking whether or not the <code>ArrayList</code> contains the object to be added is quite expensive. If you want to ensure that the object is only added once, I'd follow the recommendation made below of using a <a href="http://download.oracle.com/javase/6/docs/api/java/util/LinkedHashSet.html" rel="noreferrer">LinkedHashSet</a>. According to the API, when attempting to <a href="http://download.oracle.com/javase/6/docs/api/java/util/HashSet.html#add%28E%29" rel="noreferrer">add</a> to this data structure it</p> <blockquote> <p>Adds the specified element to this set if it is not already present. More formally, adds the specified element e to this set if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false.</p> </blockquote>
 

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