I am trying to add a method to an existing class BinaryTree<T>
to simple add the values of all the elements in the tree. The problem is that being the class a generic one, not all the types that can be send at the time of creating a tree can be added. I mean, for example It wouldn't make any sense to try to add the values of a class people
.
So my question is, how do I make a method public T addAllElements()
that only allows T
to be an specific kind of type, in this case, only the types that is possible to add it's value, like Integer
, Float
, Long
, etc? I guess there have to be some kind of numerical interface or maybe some kind of declaration provided by the language to do something like that.
By the way, it seems to be a solution without having to create a child class, in case that it could help in anything, because I was asked to solve a similar problem and the instructions says that the method have to be in the same class.
Trying to be more clear, I'll ask another question , because I think that both of them have the same answer.
I found that the method sort()
in java.util.Arrays
class can be used by a class if the class implements the interface Comparable<T>
. So if I hava a class, lets say
public class People {
implements Comparable<People>
private String name;
public int compareTo(People o) {
...
}
...
}
This class can be sorted with the sort()
method from the Arrays
class, but if the class dind't implement the Comparable<T>
interface it couldn't. So what is making this restriction in the Arrays
class definition? Is it what I need to solve the first problem I asked?