简体   繁体   English

具有多个参数的Java泛型

[英]Java generics with multiple parameters

I have seen examples on the site that deal with generics with multiple parameters but none that work for my situation. 我在网站上看到过处理具有多个参数的泛型的示例,但没有一个适用于我的情况。

So here is the deal: I am trying to learn Java generics and have decided to create a simple binary array search utility function. 所以这是交易:我正在尝试学习Java泛型,并决定创建一个简单的二进制数组搜索实用程序函数。 I am testing it out using custom objects and integers. 我正在使用自定义对象和整数进行测试。 To get feedback on errors and warning I am using Eclipse. 要获得有关错误和警告的反馈,我正在使用Eclipse。 Here is what I have: 这是我有的:

public static int binarySearch(Comparable[] array, Comparable item, int start, int end) {
    if(end < start) {
        return -1;
    }
    int mid = (start + end) / 2;
    if(item.compareTo(array[mid]) > 0) {
        return binarySearch(array, item, mid + 1, end);
    } else if(item.compareTo(array[mid]) < 0) {
        return binarySearch(array, item, start, mid - 1);
    } else {
        return mid;
    }
}

So obviously I get the warnings for Raw types saying the generics should be parameterized. 所以很明显我得到Raw类型的警告,说泛型应该参数化。 How can I do this correctly given that I have multiple parameters which both need to be the same type? 如果我有多个参数需要是同一类型,我怎么能正确地做到这一点?

SOLUTION

Here is the working solution using generics with the correct parameter checks: 以下是使用泛型和正确参数检查的工作解决方案:

public static <T extends Comparable<? super T>> int binarySearch(T[] array, T item, int start, int end) {
    if(array.length == 0) {
        return -1;
    }
    if(item == null) {
        return -1;
    }
    if(start < 0) {
        return -1;
    }
    if(end < start) {
        return -1;
    }
    int mid = (start + end) / 2;
    if(item.compareTo(array[mid]) > 0) {
        return binarySearch(array, item, mid + 1, end);
    } else if(item.compareTo(array[mid]) < 0) {
        return binarySearch(array, item, start, mid - 1);
    } else {
        return mid;
    }
}

you can specify function-specific generic parameter like so 你可以像这样指定特定于函数的泛型参数

public static <T extends Comparable<? super T>> int binarySearch(T[] arr,T elem,int start,int end){
    //...
}

This is the typical way to create generic functions: 这是创建泛型函数的典型方法:

public static <T extends Comparable<? super T>> int binarySearch(T[] array, T item, int start, int end) { ... }

For extra generality, item doesn't have to be of the same type the things in the array are, and things in the array don't have to be Comparable since you're not comparing them to anything, so 对于额外的普遍性, item 不必是同一类型的数组中的事情是,事情在阵列中不必Comparable ,因为你不比较他们什么,所以

public static <T> int binarySearch(T[] array, Comparable<T> item, int start, int end) { ... }

gives some additional flexibility. 提供额外的灵活性。

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

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