经典笔试题:有一个学生集合要求按照学生的身高从低到高排序(根据Collections.sort重载方法来实现)
package com.gaopeng.interview; public class Student { private String name; private int age; private int height; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + ", height=" + height + '}'; } }
package com.gaopeng.interview; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; public class SortStudentByHeight { public static void main(String[] args) { Student s1 = new Student(); s1.setName("张三"); s1.setAge(18); s1.setHeight(185); Student s2 = new Student(); s2.setName("李四"); s2.setAge(15); s2.setHeight(172); Student s3 = new Student(); s3.setName("王五"); s3.setAge(22); s3.setHeight(179); ArrayList<Student> studentList = new ArrayList<>(); studentList.add(s1); studentList.add(s2); studentList.add(s3); Collections.sort(studentList, new Comparator<Student>() { /** *对象比较大小方法,返回负整数、零或正整数(并没有一定要返回-1,0,1), * 根据此对象是小于、等于还是大于指定对象。 * 返回值的含义如下: * 1:对象1大于对象2 * 0:两个对象相等 *-1:对象1小于对象2 */ @Override public int compare(Student s1, Student s2) { int h1 = s1.getHeight(); int h2 = s2.getHeight(); if (h1 > h2) { return 1; } else if (h1 == h2) { return 0; } else { return -1; } } }); System.out.println(studentList); } }
运行结果如下:
[Student{name='李四', age=15, height=172}, Student{name='王五', age=22, height=179}, Student{name='张三', age=18, height=185}]