如何按私有字段对列表排序? [英] How to sort a list by a private field?

查看:83
本文介绍了如何按私有字段对列表排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的实体类如下:

public class Student {

   private int grade;

   // other fields and methods
 }

我这样使用它:

List<Student> students = ...;

考虑到这是一个私有字段,如何将studentsgrade排序?

How can I sort students by grade, taking into account that it is a private field?

推荐答案

您有以下选择:

  1. 使grade可见
  2. 定义grade
  3. 的吸气方法
  4. 在内部定义Comparator Student
  5. 使Student实现Comparable
  6. 使用反射(我认为这不是解决方案,它是解决方法/ hack )
  1. make grade visible
  2. define a getter method for grade
  3. define a Comparator inside Student
  4. make Student implement Comparable
  5. use reflection (in my opinion this is not a solution, it is a workaround/hack)


解决方案3的示例:


Example for solution 3:

public class Student {
    private int grade;

    public static Comparator<Student> byGrade = Comparator.comparing(s -> s.grade);
}

并像这样使用它:

List<Student> students = Arrays.asList(student2, student3, student1);
students.sort(Student.byGrade);
System.out.println(students);

这是我最喜欢的解决方案,因为:

This is my favorite solution because:

  • 您可以轻松定义几个Comparator
  • 代码不多
  • 您的字段保持私有和封闭状态

解决方案4的示例:

public class Student implements Comparable {
    private int grade;

    @Override
    public int compareTo(Object other) {
        if (other instanceof Student) {
            return Integer.compare(this.grade, ((Student) other).grade);
        }
        return -1;
    }
}

您可以像这样在任何地方进行排序:

You can sort everywhere like this:

List<Student> students = Arrays.asList(student2, student3, student1);
Collections.sort(students);
System.out.println(students);

此解决方案的方面:

  • 这定义为,按grade排序表示学生的自然顺序
  • 某些预先存在的方法将自动排序(例如 )
  • This defines, that sorting by grade represents the natural order of students
  • Some preexisting methods will automatically sort (like TreeMap)

这篇关于如何按私有字段对列表排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆