javaArrays.sort()实现降序排列我也是百度学到的,2333~~~
利⽤Collections的reverseOrder⽅法:
public void CollectionsSort(){
Arrays.sort(verseOrder());
for(Integer x:arr)
System.out.print(x+" ");
}
利⽤Comparator接⼝复写compare⽅法:
public void ComparatorSort(){
Comparator cmp=new MyComparator();
Arrays.sort(arr,cmp);
for(Integer x:arr)
System.out.print(x+" ");
}
//实现Comparator接⼝
public class MyComparator implements Comparator<Integer>{
@Override
public int compare(Integer arg0, Integer arg1){
// TODO ⾃动⽣成的⽅法存根
return arg0 > arg1 ?-1:1;
}
}
⽰例:实现随机数10-90之间的降序排列
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
public class TestSort {
public Integer arr[]=new Integer [10];
public void creatArr(){
for(int i=0;i<arr.length;i++)
arr[i]=(int)(Math.random()*90+10);
}
//利⽤Collections的reverseOrder⽅法:
public void CollectionsSort(){
Arrays.sort(verseOrder());
for(Integer x:arr)
System.out.print(x+" ");
}
//利⽤Comparator接⼝复写compare⽅法:
public void ComparatorSort(){
Comparator cmp=new MyComparator();
Arrays.sort(arr,cmp);
for(Integer x:arr)
System.out.print(x+" ");
}
public static void main(String[] args){
TestSort ts=new TestSort();
ts.CollectionsSort();
//ts.ComparatorSort();
nextint()方法
}
}
//实现Comparator接⼝
public class MyComparator implements Comparator<Integer>{
@Override
public int compare(Integer arg0, Integer arg1){
// TODO ⾃动⽣成的⽅法存根
return arg0 > arg1 ?-1:1;
}
}
import java.util.*;
public class Arr {
public static void main(String[] args){
// TODO ⾃动⽣成的⽅法存根
Scanner reader =new Scanner(System.in);
int n = Int();
Integer[] arr =new Integer[n];
for(int i =0; i < n; i++){
arr[i]=(int)(Math.random()*90+10);
}
Arrays.sort(arr,new Comparator<Integer>(){ public int compare(Integer a, Integer b){
return b-a;
}
});
for(int x : arr)
System.out.print(x +" ");
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。