繁体   English   中英

为什么operator <Java泛型有编译器错误?

[英]why does operator < have a compiler error for Java generics?

为什么下面的条件key < x[mid]会导致编译器抱怨操作符未定义?

在C ++中,只有当类型T不支持operator <语义时,这才是编译时警告。 你如何在Java中做同等的事情?

package search;

    public class BinarySearch<T>
    {
        public boolean binary_search_iterative (T[] x, T key)
        {
            int size = x.length;
            if ( size == 0 ) { return false; }

            int end = size - 1;

            int start = 0;

            while ( start <= end)
            {
                int mid = (end + start)/2 ;
                if (key < x[mid])
                {
                    end = mid - 1;
                }
                else if ( key > key[mid])
                {
                    start = mid + 1;
                }
                else
                {
                    return true;
                }
            }

            return false;
        }
    }

Java中没有运算符重载。 要获得类似的结果,您应该查看Comparable<T> ,它旨在为对象提供相同的功能。

所以在你的情况下它将是:

key.compareTo(x[mid]) < 0

但是为了使这个工作你必须提供一个有界类型变量, T是不够的,因为编译器无法推断出用于代替T实现Comparable所以你应该使用:

public class BinarySearch<T extends Comparable<T>>

这是因为泛型不像在C ++中那样实现,其中根据使用它们的类型在编译阶段构建模板。 您必须明确说明您的T是什么,因为类型检查器需要这样。

在Java中,您不能重载运算符。

通常解决的方法是让您的密钥类实现Comparable<T>接口,并覆盖其compareTo()方法。

然后,您可以将类型参数T限制为仅实现Comparable的类型,例如:

BinarySearch<T extends Comparable<T>>

并使用compareTo()而不是<

在C ++中,只有当类型T不支持operator <语义时,这才是编译时警告。

正确。 在Java中有没有类型T ,可以在一个通用的声明, 支持运营商<使用。 所以你得到一个编译错误。

T始终自动装箱到对象。 <仅允许java中的原始数字。

对于从Number扩展的任何原始数字或类,请尝试使用此选项:

package search;

public strictfp class BinarySearch<T extends Number>
{
    public boolean binary_search_iterative (T[] x, T key)
    {
        int size = x.length;
        if ( size == 0 ) { return false; }

        int end = size - 1;

        int start = 0;

        while ( start <= end)
        {
            int mid = (end + start)/2 ;
            if (key.doubleValue() < x[mid].doubleValue())
            {
                end = mid - 1;
            }
            else if ( key.doubleValue() > x[mid].doubleValue())
            {
                start = mid + 1;
            }
            else
            {
                return true;
            }
        }

        return false;
    }

    public static void main(String[] args) {
        BinarySearch<Integer> bs = new BinarySearch<Integer>();
        bs.binary_search_iterative(new Integer[]{1,2}, 2);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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