Reputation: 55
I knew from my java courses that when i implement an interface i have to build all the methods that exist in that interface.But when i took a look of the HashSet class i observed that it didnt build all the methods of the Set interface.Why?
Upvotes: 0
Views: 236
Reputation: 37655
HashSet
implements all the methods of the Set
interface. Not all of them appear directly in the HashSet
code because some (e.g. removeAll
) are inherited from AbstractSet
, and others (e.g. toArray
) are inherited from AbstractCollection
. You can see all this in the documentation.
These abstract classes are extremely useful. If you extend AbstractSet
, all you have to do is override size
, contains
and iterator
, and you get correctly functioning versions of other methods (e.g. containsAll
, hashCode
, toArray
, stream
) for free. You may choose to override them anyway to make them more efficient.
Upvotes: 0
Reputation: 1010
If you look at the HashSet
class declaration, you can see that besides implementing Set
, Cloneable
, and Serializable
, it extends the AbstractSet
class, which itself extends AbstractCollection
.
For example, the two toArray()
overloads are implemented in the AbstractCollection
class. So are the addAll()
, containsAll()
, retainAll()
, and removeAll()
methods. Moreover, removeAll()
is overridden in AbstractSet
.
The equals()
and hashCode()
methods, which are defined in Object
, are overridden in AbstractSet
.
Hope this helps...
Jeff
Upvotes: 3
Reputation: 1171
Take a look at the superclass, AbstractSet. From the java docs: "This class provides a skeletal implementation of the Set interface to minimize the effort required to implement this interface." HashSet extends AbstractSet so anything not implemented in AbstractSet is implemented in HashSet.
Upvotes: 0