类内排序
类内排序采用实现 Comparable 接口的方式(重写 compareTo 方法)
规则:
与本(或第一个)对象相比,若本(或第一个)对象大于另一个对象则返回1,小于则返回-1,相等则返回0;
按此规则排序是升序排序,调换返回值则反向排序。当返回0时按原相对位置排序
import java.util.Arrays;
public class Solution {
static class P implements Comparable<P>{
int n1;
int n2;
public P(int n1,int n2) {
this.n1 = n1;
this.n2 = n2;
}
@Override
public int compareTo(P p) {//按 n1 升序、n2 降序排序
if(this.n1 == p.n1) {
if(this.n2 > p.n2)
return -1;
if(this.n2 < p.n2)
return 1;
return 0;
}else {
if(this.n1 > p.n1)
return 1;
return -1;
}
}
@Override
public String toString() {
return this.n1+" "+this.n2;
}
}
public static void main(String[] args) {
P[] p = new P[45];
p[0] = new P(1, 6);
p[1] = new P(4, 5);
p[2] = new P(7, 1);
p[3] = new P(2, 4);
p[4] = new P(4, 6);
p[5] = new P(7, 2);
p[6] = new P(1, 6);
Arrays.sort(p, 0, 7);
for(int i=0; i<7; i++) {
System.out.println(p[i]);
}
/* 排序结果:
1 6
1 6
2 4
4 6
4 5
7 2
7 1
*/
}
}
类外排序
采用定义 Comparator 类型的对象(重写 compare 方法)
import java.util.Arrays;
import java.util.Comparator;
public class Solution {
static class P {
int n1;
int n2;
public P(int n1,int n2) {
this.n1 = n1;
this.n2 = n2;
}
@Override
public String toString() {
return this.n1+" "+this.n2;
}
}
public static void main(String[] args) {
P[] p = new P[45];
p[0] = new P(1, 6);
p[1] = new P(4, 5);
p[2] = new P(7, 1);
p[3] = new P(2, 4);
p[4] = new P(4, 6);
p[5] = new P(7, 2);
p[6] = new P(1, 6);
Comparator<P> cmp = new Comparator<P>() {
@Override
public int compare(P p1, P p2) {//按 n1 升序、n2 降序排序
if(p1.n1 == p2.n1) {
if(p1.n2 > p2.n2)
return -1;
if(p1.n2 < p2.n2)
return 1;
return 0;
}else {
if(p1.n1 > p2.n1)
return 1;
return -1;
}
}
};
Arrays.sort(p, 0, 7, cmp);
for(int i=0; i<7; i++) {
System.out.println(p[i]);
}
/* 排序结果:
1 6
1 6
2 4
4 6
4 5
7 2
7 1
*/
}
}