Reputation: 18923
I know what an interface is and what is a collection. But to be honest, I could not find any solid reason as why not to implement two collection interfaces in one class.
Got this question asked a few days back in an interview.
Upvotes: 1
Views: 88
Reputation: 198033
For starters, incompatible method contracts: e.g. List.add
must always return true
, and Set.add
must always return false
if the element is already present.
Upvotes: 1
Reputation: 62769
In some cases they are or can be implemented by the same object.
A Queue and a List are both implemented by LinkedList, TreeMap is both NavigableMap and SortedMap. There are a few other examples like this.
Each describes a trait or feature of the collection (exposed as a way to use it).
It just doesn't make sense all that often. For a Java collection to implement two interfaces it must be a near perfect implementation of both (and perhaps that's your answer).
A linkedlist COULD technically implement the methods of an ArrayList, however it would be a really bad idea.
Upvotes: 2
Reputation: 37645
Another point that hasn't been made already is that you can't implement the same interface twice with different type parameters.
As a result, if you tried to make a class implement both List<String>
and Collection<Integer>
, you would get a compiler error. This is because List<String>
extends Collection<String>
so we're trying to implement Collection
twice with different type parameters.
If you did manage to implement two collection interfaces at once, it would have to be like the LinkedList
example (where the generic type is the same when you think of it as a List
and when you think of it as a Deque
).
Upvotes: 1