gpt4 book ai didi

java - Comparable 使用未经检查或不安全的操作

转载 作者:行者123 更新时间:2023-11-29 05:11:11 25 4
gpt4 key购买 nike

我在尝试实现排序类时遇到了问题。我不想覆盖我在其他类中的 compareTo 方法,但如果我不使此类抽象化,那就是它要求我做的。有什么办法可以解决这个问题吗?

比较方法

public int compareTo(Course other)
{
if(this.getPoints() > other.getPoints())
return 1;
else if(this.getPoints() == other.getPoints())
return 0;
else
return -1;
}

排序类

public abstract class Sorting implements Comparable<Course>

{

public static void Sorting(Comparable[] arr)
{
int min;
Comparable temp;

for(int i = 0; i < arr.length-1; i++)
{
min = i;
for(int scan = i + 1; scan < arr.length; scan++)
{
if(arr[scan].compareTo(arr[min]) < 0)
min = scan;

temp = arr[min];
arr[min] = arr[i];
arr[i] = temp;
}
}
}//end Sorting
}//end class Sorting

这些是我得到的错误/警告

    Sorting.java:14: warning: [unchecked] unchecked call to compareTo(T) as a member
of the raw type Comparable
if(arr[scan].compareTo(arr[min]) < 0)
^
where T is a type-variable:
T extends Object declared in interface Comparable
Sorting.java:17: warning: [unchecked] unchecked conversion
temp = arr[min];
^
required: Comparable<Course>
found: Comparable
2 warnings

我假设这是因为 compareTo 接受了 Course other,但我传入了 arr[min],如果是这样,我该如何更改它以使其工作?

最佳答案

应该是

class Course implements Comparable<Course> {
public int compareTo(Course other){...}
...
}

public abstract class Sorting {
public static void sorting(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;
}
Course temp = arr[min];
arr[min] = arr[i];
arr[i] = temp;
}
}
}//end Sorting
}

或者,您可以简单地使用

public static void sorting(Course[] arr){
Arrays.sort( arr );
}

关于java - Comparable 使用未经检查或不安全的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28417395/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com