java 比较两个通用对象,如果一个是“更大”或“更小”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27866943/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 12:33:32  来源:igfitidea点击:

comparing two generic objects if the one is "greater" or "smaller"

javalistgenerics

提问by NhatNienne

I want to generate a binary tree with key - value pairs in their nodes.

我想在它们的节点中生成一个带有键值对的二叉树。

In my binary tree I want to implement nodes at the beginning with an insertmethod, which implements a new left node if the key is smaller than the key of the current node. Then if there is already a left node it will check again for it. The same logic follows for right/greater node inserts.

在我的二叉树中,我想用一种insert方法在开始时实现节点,如果键小于当前节点的键,则该方法实现一个新的左节点。然后,如果已经有一个左节点,它将再次检查它。右/更大节点插入遵循相同的逻辑。

I wrote my code first using the inttype because it's way easier for me to test my code before I use generics (new topic for me). It worked when using intbut I an unsure how to compare two generics with themselves by using "<" or ">".

我首先使用int类型编写代码,因为在使用泛型之前测试代码对我来说更容易(对我来说是新主题)。它在使用时有效,int但我不确定如何使用“<”或“>”将两个泛型与其自身进行比较。

public ListCell<Type> checkKey(Type key, ListCell<Type> checkCell) {
    ListCell<Type> newCell = null;
    if (key < checkCell.key && checkCell.left != null) {
        ...
    }
    ...
}

I don't know if it's worth saying but I'm creating my binary tree with a selfcoded list. Above you can see my current checks but i can't compare my given key now with checkCell.key because of them not being numbers.

我不知道这是否值得说,但我正在创建带有自编码列表的二叉树。在上面您可以看到我当前的支票,但我现在无法将给定的密钥与 checkCell.key 进行比较,因为它们不是数字。

So my general question ishow to compare the keys in generics if they are "smaller" or "greater" than the other for my implementation in a binary tree.

所以我的一般问题是如何比较泛型中的键,如果它们比我在二叉树中的实现中的另一个“小”或“大”。

Thanks in advance

提前致谢

回答by Andy Brown

You would need to ensure that your generic type implemented the Comparableinterface, and then use the compareTomethod instead. Java does not support overloading the >operator (or any operator overloading, for that matter).

您需要确保您的泛型类型实现了Comparable接口,然后改用该compareTo方法。Java 不支持>运算符重载(或任何运算符重载,就此而言)。

As per the documents, compareTo:

根据文件compareTo

Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

当此对象小于、等于或大于指定对象时,返回一个负整数、零或正整数。

An example (that you'll have to map on to your exact code), assuming that keyis your item you will store in your node, and checkCell.keyis your node

一个示例(您必须映射到您的确切代码),假设这key是您将存储在节点中的项目,并且checkCell.key是您的节点

int compareResult = key.compareTo(checkCell.key);
if (key < 0) { // it goes on the left }
else if (key == 0) { // it is the same }
else { // it goes on the right }

In your compareTomethod you need to decide what fields in your class determine it's "ordering". For example, if you have a sizeand priorityfield, you might do:

在您的compareTo方法中,您需要决定类中的哪些字段确定它的“排序”。例如,如果你有一个sizeandpriority字段,你可以这样做:

@Override public int compareTo(Type other) {
  final int BEFORE = -1;
  final int EQUAL = 0;
  final int AFTER = 1;

  if (this == other) return EQUAL;

  if (this.size < other.size) return BEFORE;
  else if (this.size > other.size) return AFTER;
  else { // size is equal, so test priority
    if (this.priority < other.priority) return BEFORE;
    else if (this.priority > other.priority) return AFTER;
  }
  return EQUAL;
}

回答by activedecay

Bounded type parameters are key to the implementation of generic algorithms. Consider the following method that counts the number of elements in an array T[] that are greater than a specified element elem.

有界类型参数是实现泛型算法的关键。考虑以下方法,该方法计算数组 T[] 中大于指定元素 elem 的元素数。

public static <T> int countGreaterThan(T[] anArray, T elem) {
    int count = 0;
    for (T e : anArray)
        if (e > elem)  // compiler error
            ++count;
    return count;
}

The implementation of the method is straightforward, but it does not compile because the greater than operator (>) applies only to primitive types such as short, int, double, long, float, byte, and char. You cannot use the > operator to compare objects. To fix the problem, use a type parameter bounded by the Comparable<T>interface:

该方法的实现很简单,但它不能编译,因为大于运算符 (>) 仅适用于基本类型,例如 short、int、double、long、float、byte 和 char。您不能使用 > 运算符来比较对象。要解决此问题,请使用受Comparable<T>接口限制的类型参数:

public interface Comparable<T> {
    public int compareTo(T o);
}

The resulting code will be:

结果代码将是:

public static <T extends Comparable<T>> int countGreaterThan(T[] anArray, T elem) {
    int count = 0;
    for (T e : anArray)
        if (e.compareTo(elem) > 0)
            ++count;
    return count;
}

bounded type parameters

有界类型参数