java - How to allow a generic class method to be executed only by certain types of parameters? -
i trying add method existing class binarytree<t>
simple add values of elements in tree. problem being class generic one, not types can send @ time of creating tree can added. mean, example wouldn't make sense try add values of class people
.
so question is, how make method public t addallelements()
allows t
specific kind of type, in case, types possible add it's value, integer
, float
, long
, etc? guess there have kind of numerical interface or maybe kind of declaration provided language that.
by way, seems solution without having create child class, in case in anything, because asked solve similar problem , instructions says method have in same class.
trying more clear, i'll ask question , because think both of them have same answer.
i found method sort()
in java.util.arrays
class can used class if class implements interface comparable<t>
. if hava class, lets
public class people { implements comparable<people> private string name; public int compareto(people o) { ... } ... }
this class can sorted sort()
method arrays
class, if class dind't implement comparable<t>
interface couldn't. making restriction in arrays
class definition? need solve first problem asked?
so question is, how make method
public
taddallelements()
allows t specific kind of type, in case, types possible add it's value,int
,float
,long
, etc? guess there have kind of numerical interface or maybe kind of declaration provided language that.
you're looking number
.
so declaration this, if class generic:
public binarytree<t extends number> { // ... }
or if want make method generic:
public <t extends number> t addallelements() { // ... }
that said, better or worse number
not define arithmetic operations in terms of methods. knowledge there no such built-in type does.
do note types listed primitives, mean they're not compatible generics @ all. subtypes of number
(and types can used generics) wrapper types: integer
, float
, long
, etc.
Comments
Post a Comment