简体   繁体   中英

How to compare Generic type and non-generic type values in java?

The following code is checking whether the given binary tree is a binary search tree or not which is well-known code. But the problem is Node class has a generic type value.

Thus the following codes occurs errors since it compares generic type T and non-generic type int. I've tried this and that but I couldn't find the solution. I cannot use compareTo() either in this case. (Of course if I change the Node class to have int value, but I don't want to change the Node class like this.)

Any thought or idea?

public class Node<T> {
Node<T> left;
Node<T> right;
T   value;

public Node(T value) {
this.value = value;
this.left = null;
this.right = null;
}

public boolean BTisBST(Node<T> root) {
if(root == null)
return false;

return BTisBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}

public boolean BTisBST(Node<T> root, int min, int max) {
if(root == null)
return true;

if(min > root.value || root.value > max )
return false;

return  BTisBST(root.left, min, root.value && BTisBST(root.right, root.value + 1, max);
}   

The easiest solution is to change your template type,

// Now take any type(s) that are Comparable.
public class Node<T extends Comparable<T>> {
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM