That's because Set
doesn't define a pollFirst()
method, it is defined by NavigableSet, which is implemented by TreeSet
. On the other hand, to answer your question, one good reason I can think of for java to behave like that, is this, assume that later in your code you do something like this,
Set<Integer> foo = new TreeSet<Integer>();
...
foo = ExternalLibraryClass.getUnknownSetImplementation();
// At this point, how would the compiler know what 'foo' actually is?
where ExternalLibraryClass
is an arbitrary class from an arbitrary library and getUnknownSetImplementation()
is an arbitrary method that returns a Set
implementation. The important thing is that your compiler does NOT have access to the library's source code, therefore it does NOT know what Set
implementation will be returned every time getUnknownSetImplementation()
gets called.
SOME MORE ILLUSTRATION
Assume,
String whichSet = externalWebService.whichSetShouldIUse();
if(whichSet.equals("HashSet"))
foo = new HashSet()<>;
else if(whichSet.equals("TreeSet"))
foo = new TreeSet()<>;
// At this point, how would the compiler know what 'foo' actually is?