javaSE_基础(排序),javase基础排序
javaSE_基础(排序),javase基础排序
一、排序
1. 数组升序排序
java提供了一个类专门处理数组:Arrays
Integer[] arrays = new Integer[]{1,5,7,4,3};
Arrays.sort(arrays);
for (Integer array : arrays){
System.out.print(array + " ");
}
输出:1 3 4 5 7
2. 数组降序排序
Integer[] arrays = new Integer[]{1,5,7,4,3};
Arrays.sort(arrays, new Comparator<Integer>(){
@Override
public int compare(Integer arg0, Integer arg1) {
return arg1 - arg0;
}});
for (Integer array : arrays){
System.out.print(array + " ");
}
输出:7 5 4 3 1
3. 数组转集合:
String[] strs = new String[]{"1","5","4","3"};
List<String> strList = Arrays.asList(strs);
4. 集合升序排序:
Collections.sort(strList);
for (String str : strList){
System.out.print(str + "\t");
}
输出: 1345
5. 集合降序排序:
Sort默认为升序排序,降序排序需要自定义排序器。
// 降序排序
public static void sort_des(List<String> strList){
Collections.sort(strList, new Comparator<String>(){
@Override
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
});
}
6. 自定义类排序
自定义类也可以使用上面的方法进行排序,只是将排序器写到类的外面,当类的成功变量发生变化时,需要考虑去更新排序算法,容易遗漏。
有一个更好的办法,就是将排序器写到类中,让类从comparable派生,并重载compareto方法:
public class Person implements Comparable<Person>{
@Override
public int compareTo(Person o) {
return o.getAge() - this.getAge();
}
...
}
测试代码:
public static void classSort(){
Person person1 = new Person(1, 23, "张三");
Person person2 = new Person(2, 36, "李四");
Person person3 = new Person(3, 27, "王五");
List<Person> personList = new ArrayList<Person>();
personList.add(person1);
personList.add(person2);
personList.add(person3);
// 输出原始顺序
for (Person person : personList){
System.out.println(person.getId() + " - " +
person.getAge() + " - " +person.getName());
}
// 排序
System.out.println("-----------------------");
Collections.sort(personList);
// 再输出
for (Person person : personList){
System.out.println(person.getId() + " - " +
person.getAge() + " - " +person.getName());
}
}
输出:
1 - 23 - 张三
2 - 36 - 李四
3 - 27 - 王五
-----------------------
2 - 36 - 李四
3 - 27 - 王五
1 - 23 - 张三
相关文章
- 暂无相关文章
用户点评