Method inheritance Generic class comparet

Asked

Viewed 56 times

0

I’m implementing a Node class where I wanted the equals and compareTo method to be inherited from type T, but I’m not getting it. If you make a statement like this

public class Node<T extends Comparable<? super T>> implements Comparable <Node<T>>

And override the methods as shown below

@Override
public boolean equals(Object e) {
    Node<T> aux = (Node<T>) e;
    if (this.value.equals(aux.getValue()))
        return true;
    else
        return false;
}

 @Override
public int compareTo(Node<T> a) {
    int res = this.value.compareTo(a.getValue());
    return res;
} 

However the idea I have is to make the following statement that this class would inherit the type T Comparable

public class Node<T extends Comparable<? super T>>

Can you explain to me what I’m doing wrong and why it works with the first statement but not the last?

I tested this last statement by creating Node and trying to compare but it doesn’t work, for two nodes with the same string gives me that it is false, but I know that the String type implements the Comparable interface, so I think you are not inheriting the methods.

How I made the comparison was so

Node<String> a = new Node<String("1234");
Node<String> b = new Node<String("1234");
System.out.println(a.equals(b));

Output gives false

Thank you

  • Where are you calling from? Your second definition there only means that the generic you expect extends a comparable, the first says so and also implements the comparable, ie, you could even pass the Ode itself

  • I’m calling the compareTo in my main, I just created two Node<String> with the same String and saw if they were equal, which turned out false. However, if you override the compareTo in the Node class already works. What I wanted was not to have to override the compareTo in the Node class and inherit this Override of the type that is used in the Node

  • As I understand it, if I use the first definition I can compare two Node directly because I implement the method to make the comparison, if I use the second statement I can’t compare two Node directly, I can only compare the type T that was passed, this is it?

  • no, the equals you picked up in the example are coming from Object, not from the comparable string, the second statement is only stating what you expect to get ni your generic, nothing else besides

  • There is no way to "inherit the T-type methods". If you want to compare Nodes, you need to overwrite the equals and compareTo in class Node. If you do not overwrite, they are inherited from Object (and the equals of Object compares whether objects are the same instance, so returns false if you don’t overwrite)

  • Thanks Lucasmiranda and hkotsubo already realized. I was trying to do something that is not possible, for some reason I thought that.

Show 1 more comment
No answers

Browser other questions tagged

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