Generalization of parameters in Java

3

I'm implementing a B-tree for a Java database job, so that it saves any object types, whether it's generic, so I'm treating it like it's Object , but in some precise code snippets of methods as compareTo() , which should be implemented, but the generic class does not provide them. What solution can I adopt?

I have the following method:

public void add (Object o){

    Node aux = addRecursive (this.raiz, o); 

   ... 

}

How to force the Object o parameter to implement the Comparable interface.

    
asked by anonymous 20.02.2016 / 18:07

2 answers

7

It's not really possible to do this. If you need the CompareTo() method on the object then you have to ensure that it exists.

There are even some gambiarras that can be made individually to be able to use classes that do not have this method, but would only be useful in a very specific situation, it is not feasible as a generic solution.

The only solution is to accept types that implement the method, ie all having the Comparable .

So:

public void add(Comparable o) {
    Node aux = addRecursive(this.raiz, o); 
    ...
}
    
20.02.2016 / 18:37
0

If your goal is to create a binary tree, there must be a factor of comparison between values. Using the Object type, you can actually collect any Java object, however it is not any object that can be compared.

One solution would be to use an interface as an argument, as this forces all collected objects to be "comparable to each other". However, if you think about it, the customer in your class will need to take extra care, because if you collect Comparable objects of different types you will have problems.

    
21.02.2016 / 02:37