- Arrays.sort()方法对引用类型(对象)排序有两种方法:
继承Comparable接口并实现compareTo方法
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
Man[] msMans = { new Man(3, "a"), new Man(60, "b"), new Man(2, "c") };
Arrays.sort(msMans);
System.out.println(Arrays.toString(msMans));
}
}
@Data
class Man implements Comparable {
int age;
int id;
String name;
public int compareTo(Object o) {
Man man = (Man) o;
if (this.age < man.age) {
return -1;
}
if (this.age > man.age) {
return 1;
}
return 0;
}
}
重写Comparator比较器的compare方法
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
Man[] msMans = { new Man(3, "a"), new Man(60, "b"), new Man(2, "c") };
Arrays.sort(Man, new Comparator<Man>() {
@SneakyThrows
@Override
public int compare(Man m1, Man m2) {
if (m1.age < m2.age) {
return -1;
}
if (m1.age > m2.age) {
return 1;
}
return 0;
}
});
System.out.println(Arrays.toString(msMans));
}
}
区别
List和Array互转:
Man[] manArray = manList.toArray(new Man[manList.size()]);
List<Man> manList = Arrays.asList(manArray);
|