当前位置: 代码迷 >> 综合 >> 对象集合排序(需要implements Comparable)
  详细解决方案

对象集合排序(需要implements Comparable)

热度:28   发布时间:2023-10-15 09:32:30.0
public class Student implements Comparable<Student> {/*** 对象的排序方式[升、降],true为升序反之降序*/private static boolean sortASC = true;/*** 对象的排序属性,根据对象自己设置的id,名字、出生日期*/private static boolean sortBybId = false;private static boolean sortBybName = false;private static boolean sortBybDate = true;private String name;private String id;private int age;private Date birthDay;public Student() {}public Student(String name, String id, int age, Date birthDay) {this.name = name;this.id = id;this.age = age;this.birthDay = birthDay;}@Overridepublic int compareTo(@NonNull Student o) {if (sortBybId) {int id1 = Integer.valueOf(this.id);int id2 = Integer.valueOf(o.id);if (sortASC) {return id1 > id2 ? 1 : id1 == id2 ? 0 : -1;} else {return id1 > id2 ? -1 : id1 == id2 ? 0 : 1;}} else if (sortBybName) {if (sortASC) {return this.name.compareTo(o.name);} else {int result = this.name.compareTo(o.name);return result > 0 ? -1 : result == 0 ? 0 : 1;}} else if (sortBybDate) {if (sortASC) {return this.birthDay.compareTo(o.birthDay);} else {int result = this.birthDay.compareTo(o.birthDay);return result > 0 ? -1 : result == 0 ? 0 : 1;}}//返回 1是默认值return 1;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getId() {return id;}public void setId(String id) {this.id = id;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public Date getBirthDay() {return birthDay;}public void setBirthDay(Date birthDay) {this.birthDay = birthDay;}@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", id='" + id + '\'' +", age='" + age + '\'' +", birthDay=" + birthDay +'}' + "\n";}
}


外部调用:

public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Student[] students = (Student[]) generateData().toArray(new Student[]{});Arrays.sort(students);List<Student> newList = Arrays.asList(students);for (Student student : newList) {Log.e("MainActivity", student.toString());}}private List<Student> generateData() {List<Student> students = new ArrayList<>();students.add(new Student("Cy", "01", 22, getDate("1992-10-20")));students.add(new Student("Yl", "03", 23, getDate("1993-10-16")));students.add(new Student("Hk", "02", 21, getDate("1993-06-05")));students.add(new Student("Ly", "04", 24, getDate("1990-07-13")));students.add(new Student("Xlp", "06", 19, getDate("1994-01-11")));students.add(new Student("Spl", "05", 22, getDate("1992-05-14")));return students;}private Date getDate(String date) {try {return new SimpleDateFormat("yyyy-MM-dd").parse(date);} catch (ParseException e) {e.printStackTrace();}return null;}
}


  相关解决方案