经典笔试题:有一个学生集合要求按照学生的身高从低到高排序(list中的对象实现Comparable接口来实现)
package com.gaopeng.interview; public class StudentHasComp implements Comparable<StudentHasComp> { private String name; private Integer age; private Integer height; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Integer getHeight() { return height; } public void setHeight(Integer height) { this.height = height; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + ", height=" + height + '}'; } /** * 返回 0 表示 this == obj * 返回整数表示 this > obj * 返回负数表示 this < obj */ @Override public int compareTo(StudentHasComp shc) { return this.getHeight().compareTo(shc.getHeight()); } }
package com.gaopeng.interview; import java.util.ArrayList; import java.util.Collections; public class SortStudentHasCompByHeight { public static void main(String[] args) { StudentHasComp s1 = new StudentHasComp(); s1.setName("张三"); s1.setAge(18); s1.setHeight(185); StudentHasComp s2 = new StudentHasComp(); s2.setName("李四"); s2.setAge(15); s2.setHeight(172); StudentHasComp s3 = new StudentHasComp(); s3.setName("王五"); s3.setAge(22); s3.setHeight(179); ArrayList<StudentHasComp> studentList = new ArrayList<>(); studentList.add(s1); studentList.add(s2); studentList.add(s3); Collections.sort(studentList); System.out.println(studentList); } }
运行结果如下:
[Student{name='李四', age=15, height=172}, Student{name='王五', age=22, height=179}, Student{name='张三', age=18, height=185}]