Collections.sort通过对给定的数组进行排序给了我一个错误



我知道我可以使用"Arrays.sort(temprature(;"来排序 但我想知道为什么收集方法不起作用,因为它有最大值、最小值、反向等......在其中。

import java.util.Collections;
public class sortingTheArray {
public static void main(String[] args) {
int [] temprature =  {9,8,5,13,7,17,5,14,9,5,18};
for (double ar : temprature) {
System.out.println(ar); 
}
Collections.sort(temprature);
for (double ar : temprature) {
System.out.println(ar);
}
Collections.reverse(temprature);
for (double ar : temprature) {
System.out.println(ar);
}
}
}

此错误是因为您在数组上使用Collections.sort。数组不是 Java 集合,请尝试改用 Arrays.sort。

1(类的名称最好用大写的第一个字母书写。(公约(

2(您应该提供您得到的错误。

3( 该方法不起作用,因为您正在对数组调用集合方法,而集合适用于列表。要对数组进行排序,您可以将其转换为列表或使用各种排序方法(插入、选择、冒泡,...(对其进行排序。

您正在使用原语数组,我们不能有基元类型列表(java 7 及更低版本(。所以首先更改数组

从这个int [] temprature = {9,8,5,13,7,17,5,14,9,5,18};到这个Integer[] temprature = {9,8,5,13,7,17,5,14,9,5,18};

现在,您可以将其更改为列表List<Integer> list = new ArrayList<>(Arrays.asList(temprature));并执行排序,反向,最大值,最小值等操作。

public class SortingTheArray {
public static void main(String[] args) {
Integer [] temprature =  {9,8,5,13,7,17,5,14,9,5,18};
for (double ar : temprature) {
System.out.println(ar); 
}
List<Integer> list = new ArrayList<>(Arrays.asList(temprature));
Collections.sort(list);
for (double ar : list) {
System.out.println(ar);
}
Collections.reverse(list);
for (double ar : list) {
System.out.println(ar);
}
System.out.println("Max Value : " + Collections.max(list));
System.out.println("Min Value : " + Collections.min(list));
}

}

编辑 1 - 如果您使用的是java 8,则可以使用Arrays.stream((来创建原语列表。

int [] temprature2 =  {9,8,5,13,7,17,5,14,9,5,18};
List<Integer> list2 = Arrays.stream(temprature2).boxed().collect(Collectors.toList());

相关内容

最新更新