Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does LinkedHashSet<E> extend HashSet<e> and implement Set<E>

Opened a LinkedHashSet source code today and found some interesting thing:

public class LinkedHashSet<E>     extends HashSet<E>     implements Set<E>, Cloneable, java.io.Serializable { 

The question is: why do they need both "extends HashSet" and "implements Set" when HashSet already is the Set?

like image 465
zeroed Avatar asked Jan 29 '10 21:01

zeroed


People also ask

Does LinkedHashSet extend HashSet?

The LinkedHashSet class extends the HashSet class, which implements the Set interface. The Set interface inherits Collection and Iterable interfaces in hierarchical order.

Does LinkedHashSet implement HashSet?

Both LinkedHashSet and HashSet implements the Set interface. However, there exist some differences between them. LinkedHashSet maintains a linked list internally. Due to this, it maintains the insertion order of its elements.

Does LinkedHashSet implements set?

When cycling through LinkedHashSet using an iterator, the elements will be returned in the order in which they were inserted. Contains unique elements only like HashSet. It extends the HashSet class and implements the Set interface.

What is the advantage of LinkedHashSet over HashSet?

HashSet is an unordered & unsorted collection of the data set, whereas the LinkedHashSet is an ordered and sorted collection of HashSet. HashSet does not provide any method to maintain the insertion order. Comparatively, LinkedHashSet maintains the insertion order of the elements.


2 Answers

I've asked Josh Bloch, and he informs me that it was a mistake. He used to think, long ago, that there was some value in it, but he since "saw the light". Clearly JDK maintainers haven't considered this to be worth backing out later.

like image 154
Kevin Bourrillion Avatar answered Sep 25 '22 17:09

Kevin Bourrillion


They didn't need to explicitly write implements Set<E>. They did it for readability.

like image 28
sepp2k Avatar answered Sep 22 '22 17:09

sepp2k