Posts

Showing posts with the label encapsulation

How to sort a list by a private field?

My entity class looks like this: public class Student { private int grade; // other fields and methods } and I use it like that: List<Student> students = ...; How can I sort students by grade, taking into account that it is a private field? You have these options: make grade visible define a getter method for grade define a Comparator inside Student make Student implement Comparable use reflection (in my opinion this is not a solution, it is a workaround/hack) Example for solution 3: public class Student { private int grade; public static Comparator<Student> byGrade = Comparator.comparing(s -> s.grade); } and use it like this: List<Student> students = Arrays.asList(student2, student3, student1); students.sort(Student.byGrade); System.out.println(students); This is my favorite solution because: You can easily define several Comparators It is not much code Your field stays private and encapsulated Example of solution 4: public class Student implem...