简体   繁体   English

通用方法-无法应用于给定类型

[英]Generic method - cannot be applied to given types

I am working on my first program that utilizes a generic method. 我正在开发使用通用方法的第一个程序。 I thought I was doing it correctly by setting the parameter to selectionSort(T[] a) so the method could receive an array of any object. 我以为我可以通过将参数设置为selectionSort(T[] a)来正确地进行操作,因此该方法可以接收任何对象的数组。

public class SelectionSort {
protected int[] arrayOne = {1,2,3,4,5,6,7,8};
protected double[] arrayTwo = {1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0};
public static <T extends Comparable<T>> void selectionSort(T[] a)
{
for (int index =0; index < a.length; index++)
{
    int minElementIndex = index;
    T minElementValue = a[index];
    for (int i = index + 1; i < a.length; i++) 
    {
        if (a[i].compareTo(minElementValue) < 0)
        {
            minElementIndex = i;
            minElementValue = a[i];
        }
    }//end of inner for loop
    a[minElementIndex] = a[index];
    a[index] = minElementValue;
}//end of outer for loop
for(int indexb = 0; indexb<a.length; indexb++)
{
    System.out.printf("%d ", a[indexb]);
    if(indexb == a.length)
        System.out.println("");
}
}
public static void main(String[] args)
{
selectionSort(arrayOne);
selectionSort(arrayTwo);

}}//end of main and SelectionSort

Perhaps you can help me out. 也许你可以帮帮我。 If so I would greatly appreciate it. 如果是这样,我将不胜感激。

Generics cannot be used with primitive types like int or double , which are not objects or classes. 泛型不能与基本类型(例如intdouble ,它们不是对象或类。 You will have to use the boxed versions Integer[] and Double[] . 您将不得不使用盒装版本Integer[]Double[]

In particular, if you want to support accepting primitive int[] and double[] arrays, you will have to write the code twice. 特别是,如果要支持接受原始的int[]double[]数组,则必须编写两次代码。 =( (I can think of one semi-workaround, but not without using external libraries...) =((我可以想到一种半解决方法,但一定要使用外部库...)

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

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