Mario Boley
Mario Boley

Reputation: 391

Java collection interface that guarantees no duplicates as well as preservation of insertion order

Is there a java collection interface that guarantees no duplicates as well as the preservation of insertion order at the same time?

This is exactly what LinkedHashSet is doing? However, I am wondering if there is also an interface guaranteeing the same thing in order to avoid direct dependency on some specific class?

SortedSet is referring only to the natural order (and is not implemented by LinkedHashSet).

Essentially, I am looking for an interface that would indicate that the iteration order of elements is significant (and at the same time it contains no duplicates, i.e., List obviously would not apply).

Thanks!

UPDATE this question is not asking for an implementation or a data structure (as in the question to which this was marked as a duplicate). As several people pointed out as clarification, I am looking for an interface that demands both properties (no duplicates and significant order) in its contract. The application for this would be that I can return objects of this type to clients without promising any specific implementation.

UPDATE 2 Moreover, the related question specifically asks for preserving duplicates in contrast to this question. So I am pretty certain it is not a duplicate.

Upvotes: 1

Views: 2116

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 148870

No interface in the JDK collections provides that.

You could try to build it by combining Set and List. Any collection implementing Set should not allow duplicate elements, and any collection implementing List should maintain order.

But then, no class in the JDK collection implements both Set and List. Because unfortunately LinkedHashSet does not implement List.

Of course, you could build one implementation easily by wrapping a LinkedHashSet (by composition patter, not by derivation) and adding a get(int i) method, or by wrapping an ArrayList (again by composition) and throwing an IllegalArgumentException when trying to add a new element.

The most tricky part IMHO would be the addAll method as both interfaces define it with different semantics (emphasize mine) :

  • Set: Adds all of the elements in the specified collection to this set if they're not already present
  • List : Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator

As you cannot meet both requirements is source collection contains duplicates, my advice would be that addAll throws an IllegalArgumentException in that case, or more simply that it always throw an UnsupportedOperationException as addAll is an optional operation for both interfaces

Upvotes: 4

Related Questions