当前位置: 移动技术网 > IT编程>开发语言>Java > JAVA基于Arrays.sort()实现数组升序和降序

JAVA基于Arrays.sort()实现数组升序和降序

2020年06月14日  | 移动技术网IT编程  | 我要评论

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);
    }
  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网