java:Comparator-自定义比较
2018-01-15 22:19
155 查看
具体的使用方法代码示例:
public void testSort3() { List<Student> studentList = new ArrayList<Student>(); Random random = new Random(); studentList.add(new Student(random.nextInt(1000) + "", "Mike"));//int+string类的空值=string类 studentList.add(new Student(random.nextInt(1000) + "", "Angela")); studentList.add(new Student(random.nextInt(1000) + "", "Lucy")); studentList.add(new Student(10000 + "", "Beyonce")); Collections.sort(studentList, new StudentComparator());//将集合按照StudentComparator这个类所实现的比较方法来排序 System.out.println("----------------按照姓名排序后-----------------"); for (Student student : studentList) { System.out.println("学生:" + student.id + ":" + student.name); } }StudentComparator类:
import java.util.Comparator; public class StudentComparator implements Comparator<Student> { @Override public int compare(Student o1, Student o2) {//重写compare方法,规定将Student的name属性作为比较条件。 // TODO Auto-generated method stub return o1.name.compareTo(o2.name); } }
相关文章推荐
- Java编程之TreeSet排序两种解决方法(1)元素自身具备比较功能,元素需要实现Comparable接口覆盖compare(2)创建根据自定义Person类的name进行排序的Comparator
- java学习(十六):对象的自定义比较,Comparator和Comparable
- java 第八篇 使用comparator实现自定义排序
- Java中Comparable和Comparator实现对象比较
- 用来比较的java接口,Comparator 和 Comparable
- Java 中 Comparable 和 Comparator 比较
- Java中实现对象的比较:Comparable接口和Comparator接口
- Java 中 Comparable 和 Comparator 比较
- 关于JAVA的排序函数的比较——comparator,comparatable
- Java 中 Comparable 和 Comparator 比较
- [原创]Java使用反射及自定义注解实现对象差异性比较
- Java 中 Comparable 和 Comparator 比较
- 浅谈Java的Comparator接口实现自定义排序Arrays.sort()
- java中利用Comparator接口实现自定义排序技巧。
- Java中使用Comparable与Comparator实现比较
- 比较java comparable和Comparator 区别
- java基础—自定义一个比较器,按照字符串的长度升序的方法来比较字符串进行储存(java集合三)
- java比较自定义对象相等的方法
- Java Comparator的双重比较问题
- Java中Comparable和Comparator实现对象比较