Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>A simple approach in Java would be to create a wrapper class that implements both the <code>Set</code> and <code>List</code> interfaces, and that contained both a <code>HashSet</code> and <code>ArrayList</code>. Update operations would need to update both internal collections, and read operations would be mapped to whichever internal collection gives the correct semantics and best performance. The only slightly tricky method is <code>iterator()</code> where you need to arrange that <code>remove</code> updates both collections.</p> <p>This approach will give you the "best of both worlds" performance for read operations, but updates will necessarily be slower. In particular, insert at a given position and remove will be <code>O(N)</code> operations.</p> <p>(I'd note that LinkedHashSet is not a direct solution since it does not provide a <code>get(int)</code> method. You could implement this method via the LinkedHashSet iterator, by that makes it an <code>O(N)</code> operation. Probably not what you want.)</p> <p><strong>FOLLOW UP</strong></p> <p>I've not been able to find a general purpose implementation class that implements both the <code>Set</code> and <code>List</code> interfaces. I think that the reason is that there are semantic anomalies when you combine the interfaces. For example, (as @ColinD notes) if you call <code>E set(int, E)</code> with an element that it already in the list, it is not clear what the result should be. Dealing with this in a way that satisfies everyone is probably impossible, and I can understand why they might have decided not to go swimming in the tarpit.</p> <p>However, I don't see this as a major problem if you are creating a <code>Set</code> + <code>List</code> class for your application's internal use. You either </p> <ul> <li>pick a semantic for that suits your application, </li> <li>code your application to not use the method at all, or</li> <li>code your application to avoid being bitten by the anomaly.</li> </ul> <p>(For instance, you might code it to either ignore result of the <code>set</code> method, to throw an unchecked exception if there is a duplicate, or return <code>null</code> or some distinguished object if there is a duplicate.)</p> <p>For the record, it is not unforgivable for a custom collection class to violate the interface contract. Indeed, even the Java designers do it - see IdentityHashMap. What is unforgivable is not documenting the contract violations in the javadocs.</p>
 

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