Generalization of parameters in Java

Asked

Viewed 238 times

3

I am implementing a B tree for a database job in Java, so that it stores any kind of objects, be generic, so I am treating as if it were Object, but in some parts of precise code methods such 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 parameter Object o have to implement the interface Comparable.

  • You can also use the class java.util.Objects if using the interface Comparable or Comparator not feasible. This class provides utility methods for objects, see these methods here.

2 answers

7


Actually it is not possible to do this. If you need the method CompareTo() on the object then have to ensure that it exists.

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

The only solution is to accept types that implement the method, that is, all with the interface Comparable.

Thus:

public void add(Comparable o) {
    Node aux = addRecursive(this.raiz, o); 
    ...
}

I put in the Github for future reference.

  • Forgive my lack of knowledge, but how do I determine that the parameter has to implement the given interface

  • It depends, you haven’t shown how you want to use it. The question has no details, so the answer also has no.

  • If your class cannot implement the interface Comparable, you can also use the interface Comparator.

0

If your goal is to create a binary tree, there must be a comparison factor between the 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 requires 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.