【问题标题】:Inferred type does not conform to declared bound(s)推断类型不符合声明的界限
【发布时间】:2015-06-23 14:33:15
【问题描述】:

我遇到了一个我以前从未见过的错误,我不太确定如何修复它。我目前正在尝试创建一个排序类来比较数组中的成绩点,如果有帮助,我会添加它,我遇到了这个错误。

  required: Course[]
  found: Course[]
  reason: inferred type does not conform to declared bound(s)
    inferred: Course
    bound(s): Comparable<Course>
  where Course is a type-variable:
    Course extends Comparable<Course> declared in method<Course>SelectionSort(Course[])

产生此错误的类:

public class Sorting
{
    private static <Course> void swap(Course[] arr, int i, int j)
    {
        if(i != j)
        {
            Course temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    }

    //Sort method
    public <Course extends Comparable<Course>> void SelectionSort(Course[] arr)
    {
        for(int i = 0; i < arr.length-1; i++)
        {
            int min = i;
            for(int scan = i + 1; scan < arr.length; scan++)
            {
                if(arr[scan].compareTo(arr[min]) <= 0)
                    min = scan;
            }
            swap(arr,i,min);
        }
    }//end Sorting  
}//end class Sorting

不知道如何处理这样的事情,这是我必须完成的一项旧任务,但我无法弄清楚。

测试类:

public class Test1{

public static void main(String [] args)
{
    Course[] courses = new Course[7];
    Sorting sort = new Sorting();
    courses[0] = new CSInfo("CS1083", "A+", 4);
    courses[1] = new CSInfo("CS1073", "A-", 4);
    courses[3] = new MathStat("MATH1003", "C+", 3);
    courses[4] = new MathStat("MATH1013", "B-", 3);
    courses[5] = new CSInfo("CS2053", "B-", 4);
    courses[6] = new Breadth("POLS2101", "A-", 3);

    courses[0].getPoints();
    courses[1].getPoints();
    //courses[2].getPoints();
    courses[3].getPoints();
    courses[4].getPoints();
    courses[5].getPoints();
    courses[6].getPoints();

    courses[0].toString();

    sort.SelectionSort(courses);

    }

}

【问题讨论】:

  • 您是否将那些泛型方法与未实现 Comparable&lt;Course&gt; 的类 Course 一起使用?
  • 嗯,这是一个愚蠢的错误......但现在我在第 23 行的同一个类中遇到了一个空指针异常 if(arr[scan].compareTo(arr[min])
  • @Afatmunky 你如何初始化arr?
  • @Afatmunky 不,SelectionSort 对已经初始化的数组进行排序。因此,它应该在方法之外进行初始化。例如,Course[] arr = new Course[] {new Course(1, "Bla bla 101"), new Course(2, "Foo Bar 110")}。
  • @Afatmunky 顺便说一句,看起来你在这里不需要泛型。在您的代码中,Course 是类型参数的名称,而不是类本身。使用以下签名可能是合理的:private static void swap(Course[] arr, int i, int j) 和 public void SelectionSort(Course[] arr)

标签: java arrays error-handling


【解决方案1】:

看来你没有初始化数组成员,数组没问题,因为nullpointer不在for循环中(arr.length)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-12
    • 1970-01-01
    • 2020-05-04
    • 2012-03-13
    • 1970-01-01
    相关资源
    最近更新 更多