关于JAVA 排序(sort)用法总结

简单类型数组排序

  • Arrays.sort(数组名)默认升序排列
  • Arrays.sort(数组名,起始地址,结束地址)
  • 倘若改变排列方式,需要重写compare 方法
  • 并且需要将其转换为Integer(int 的包装类)类型
int [] array = new int[] {1, 3, 5, 7, 9, 2, 4, 6, 8, 10};
    Arrays.sort(array);
    for(int x : array)
	System.out.println(x);

 改变默认排序方式

Integer[] arrays = new Integer[m];
	for(int i = 0; i < m; i++) {
		arrays[i] = sc.nextInt();
        }
	Arrays.sort(arrays, new Comparator<Integer>(){

		@Override
		public int compare(Integer o1, Integer o2) {
			if(o1 < o2) return -1;
			else return 1;
		}
			
	});
	for(int x : arrays)
		System.out.print(x + " ");

 

复杂类型数组(类数组)排序

  • 需要重写Comparator接口提供的方法
  • 通过匿名内部类和普通类重写
  • 不同的重写方法,sort 参数内容不同
Arrays.sort(array, new Comparator<Sortway_1>(){

	@Override
	public int compare(Sortway_1 o1, Sortway_1 o2) {
		if(o2.score > o1.score) return 1;
		else return -1;
	}	
	
});
class Compare implements Comparator <Sortway_2>{

	@Override
	public int compare(Sortway_2 o1, Sortway_2 o2) {
		if(o2.score > o1.score) return -1;
		else return 1;
	}
	
}
Arrays.sort(array, new Compare());

完整代码

import java.util.Arrays;
import java.util.Comparator;

public class Sort_1 {
	public String number;
	public int score;
	public Sort_1(String number, int score) {
		this.number = number;
		this.score = score;
	}
	
	public static void main(String[] args) {
		Sort_1 [] array = {new Sort_1("22170001", 99),
						    new Sort_1("22170002", 100),
						    new Sort_1("22170003", 98),
						    new Sort_1("22170024", 88),
						    new Sort_1("22170027", 95),
		};
		Arrays.sort(array, new Comparator<Sort_1>(){

			@Override
			public int compare(Sort_1 o1, Sort_1 o2) {
				if(o2.score > o1.score) return 1;
				else return -1;
			}
				
		});
		for(Sort_1 s : array)
			System.out.println(s.number + " " + s.score);
	}

}

通过匿名内部类创建要更直观简单一些

import java.util.Arrays;
import java.util.Comparator;

class Compare implements Comparator <Sort_2>{

	@Override
	public int compare(Sort_2 o1, Sort_2 o2) {
		if(o2.score > o1.score) return -1;
		else return 1;
	}
	
}

public class Sort_2 {
	public String number;
	public int score;
	
	public Sort_2(String number, int score) {
		this.number = number;
		this.score = score;
	}
	
	public static void main(String[] args) {
		Sort_2 [] array = { new Sort_2("22170001", 99),
			    			   new Sort_2("22170002", 100),
			    			   new Sort_2("22170003", 98),
			    			   new Sort_2("22170024", 88),
			    			   new Sort_2("22170027", 95),
        };
		Arrays.sort(array, new Compare());
		for(Sort_2 s : array)
			System.out.println(s.number + " " + s.score);
	}

}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值