Why doesn't LinkedHashSet implement List?

969 views Asked by At

To my understanding, a List is an ordered collection of items. And a Set is a collection of unique items.

Now my question is, why does LinkedHashSet, which describes an ordered collection of unique items, implement the Set interface (=> unique), but not the List interface (=> ordered)?

One possible argument is that List is intended for random access datastructures, but that would be invalidated by the fact that LinkedList doesn't have "true" random access either. In fact, LinkedHashSet is backed by an internal linked list. Also the documentation for List says otherwise:

Note that these [positional index] operations may execute in time proportional to the index value for some implementations.

2

There are 2 answers

2
chetan mehra On

because LinkHashSet is class which implements set interface . List and Set has its own functionality List allowed duplicates while set do not allowed duplicates but if you want linear order insertion in a HastSet then LinkedHashSet is used with no duplicates in itself ..

Set s = new LinkedHashSet();

is the implementation of a set in which insertion order is preserved and duplicates do not allowed..

6
xenteros On

If it implemented a List you would be able to use it as a List:

List list = new LinkedHashSet();

This might lead to issues with duplicates which don't appear in Set but are allowed in List.

In other words, you shouldn't declare that something is a List when it doesn't allow duplicates even if it holds the order and allows adding, getting, removing and checking the size.

Unlike sets, lists typically allow duplicate elements
--List documentation