Generic and Comparable in Java

4

I have a question that I can not answer, if anyone can give me a plausible explanation, I'll be grateful.

Assuming I have 2 classes:

public class Figura implements Comparable<Figura>
{
    private final int largura, altura;

    Figura(int l, int a)
    {
        largura = l;
        altura = a;
    }

    @Override
    public int compareTo(Figura o) 
    {
        if((o.largura*o.altura) > (this.altura * this.largura))
            return 0;
        else
            return 1;
    }


}


public class Rectangulo extends Figura 
{
    Rectangulo(int altura, int largura)
    {
        super(altura, largura);
    }


}

When I try to create a generic method that lets you compare 2 elements, if you do:

 public static <T> int comparaRect(T rect, Comparable<? super T>  outroRect)
 {
     return outroRect.compareTo(rect);
 }

It works without a problem. But if you do:

  public static <T> int comparaRect(T rect, Comparable<? super T>  outroRect)
     {
         return rect.compareTo(outroRect);
     }

No longer works. Getting the error can not find symbol T etc.

My question here is: Why can I only do it one way and not both, once one element is inherited from the other and then also inherits the comparable interface Figure?

Thank you in advance.

    
asked by anonymous 04.11.2017 / 19:32

1 answer

2
  

My question here is: Why can I only do it one way and not both, once one element is inherited from the other and then also inherits the comparable interface Figure

The problem has no relation to inheritance, the problem is in the way the method was mounted:

public static <T> int comparaRect(T rect, Comparable<? super T>  outroRect) {
   return rect.compareTo(outroRect);
 }

In this way, the compiler can not guarantee (in a secure way) that T is an instance that implements / contains the compareTo method, T rect.

If you want to perform the operation with both arguments, the method must be muting in a different way:

public static <T extends Comparable<T>> int comparaRect(T rect, T outroRect) {
   return outroRect.compareTo(rect);
}

Or:

public static <T extends Comparable<T>> int comparaRect(T rect, T outroRect) {
   return rect.compareTo(outroRect);
}

This ensures that both T arguments implement the Comparable interface.

    
05.11.2017 / 14:00