java中对数组进行排序

使用Array.sort() 这个默认是升序

    @Test
    public void index4(){
        int scores[] = new int[]{1,2,3,89,4};
        Arrays.sort(scores);
        for (int i:scores
        ) {
            System.out.println(i);
        }
    }

如果想降序怎么办呢?

使用:Arrays.sort(scores,Collections.reverseOrder());

需要注意的是 不能使用基本类型(int,double, char),如果是int型需要改成Integer,float要改成Float

例子:

    @Test
    public void index5(){
        Integer scores[] = {1,2,3,89,4};
        Arrays.sort(scores,Collections.reverseOrder());
        for (Integer i:scores
        ) {
            System.out.println(i);
        }
    }

如果得到的是int数组,怎么办,需要先转换一下

    @Test
    public void index6(){
        int scores[] = new int[]{1,2,3,89,4};
        Integer newScores[] = new Integer [5];
        for(int i=0;i<scores.length;i++){
            newScores[i]= new Integer(scores[i]);
        }

        Arrays.sort(newScores,Collections.reverseOrder());
        for (Integer i:newScores
        ) {
            System.out.println(i);
        }
    }

 

相关文章:

  • 2022-12-23
  • 2021-08-16
  • 2022-01-22
  • 2021-11-19
  • 2021-11-24
  • 2021-12-22
  • 2022-12-23
  • 2021-11-12
猜你喜欢
  • 2021-08-06
  • 2022-01-26
  • 2022-12-23
  • 2022-12-23
  • 2021-07-09
  • 2021-07-14
  • 2022-03-08
相关资源
相似解决方案