Collections.sort通过给定数组排序给我一个错误

时间:2018-10-23 21:25:32

标签: java collections

我知道我可以使用“ 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);
        }
    }
}

3 个答案:

答案 0 :(得分:2)

此错误是因为您在数组上使用g = seaborn.FacetGrid(df,"month") g.map(plt.plot,"day","values") 。数组不是Java集合,请尝试使用Arrays.sort。

答案 1 :(得分:0)

1)最好使用大写的第一个字母来编写类的名称。 (惯例)

2)您应该提供了所得到的错误。

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

答案 2 :(得分:0)

您使用的是原始数组,我们无法提供原始类型的列表(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());