java - Why can't I use .pollFirst() method for a Set that was initialized as a TreeSet? -
say i've intialized set
new treeset
:
set<integer> foo = new treeset<integer>();
and want use .pollfirst()
method, because i'm lazy , don't want have use temp variable because have handy method reduce otherwise 3-4 lines of code 1 line.
however, following code, way compile code call foo
treeset
.
while (foo.size() > 1) { int lower = foo.pollfirst(); int higher = foo.pollfirst(); foo.add(higher - lower); }
so why java doesn't realize foo
treeset
? should cast treeset
if didn't want intialize foo
treeset
? or better intialize way?
further testing casting:
while (foo.size() > 1) { int lower = (int) ((treeset) foo).pollfirst(); int higher = (int) ((treeset) foo).pollfirst(); foo.add(higher - lower); }
this makes compile without explicitly calling treeset
upon intialization.
that's because set
doesn't define pollfirst()
method, defined navigableset, implemented treeset
. on other hand, answer question, 1 reason can think of java behave that, this, assume later in code this,
set<integer> foo = new treeset<integer>(); ... foo = externallibraryclass.getunknownsetimplementation(); // @ point, how compiler know 'foo' is?
where externallibraryclass
arbitrary class arbitrary library , getunknownsetimplementation()
arbitrary method returns set
implementation. important thing compiler not have access library's source code, therefore not know set
implementation 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()<>; // @ point, how compiler know 'foo' is?
Comments
Post a Comment