I want to implement the Comparable interface, and use it to make a comparison (and subsequent sorting) of array elements according to the LocalDate field. The code below gives the error dateOfAdmission cannot be resolved or is not a field. I was advised to read the help from oraclela https://docs.oracle.com/javase/8/docs/api/java/time/chrono/ChronoLocalDate.html , but due to the fact that my English so far consists of troubles and chagrin, I understood a little. I ask you to explain to me what the error is and how it should be done so that I can compare objects across a field like LocalDate. Thanks in advance. ps: cloning is not added

package myDefault; import java.time.*; import java.util.*; /*В данной программе ставлю целью повторить пройденный материал по сравнению и клонированию объектов*/ public class Student implements Comparable<LocalDate>, Cloneable { private String firstName; private String lastName; LocalDate dateOfAdmission; int scholarship; Student(String firstName, String lastName, int day, int month, int year, int scholarship) { this.firstName = firstName; this.lastName = lastName; dateOfAdmission = LocalDate.of(day,month,year); this.scholarship = scholarship; } public int compareTo(LocalDate other) { return Double.compare(dateOfAdmission, other.dateOfAdmission); } public void fillArray() { Student[] arrayOfStudents = new Student[3]; Student petya = new Student("Petya","Popov",10,6,2017,1500); Student vasya = new Student("Vasya","Ovsyannikov",5,6,2017,1500); Student gena = new Student("Gena","Lolov",12,6,2017,1500); arrayOfStudents[0] = petya; arrayOfStudents[1] = vasya; arrayOfStudents[2] = gena; } public void createNewArray() { Student[] newArray = new Student[3]; } public void outputArray(Student[] arrayOfStudents) { int counter; for(counter = 0; counter < 3; counter++) { System.out.println(arrayOfStudents[counter]); } } public Student clone() throws CloneNotSupportedException { Student cloned = (Student) super.clone(); return cloned; } 

}

  • But does LocalDate compare as Double ? You yourself must write a comparison of these fields and output 0,1,-1 - JVic

1 answer 1

You yourself must implement a comparison of two fields and not borrow someone else's. You can of course borrow someone else if it suits you. It seems to me that double does not suit you at all. Try something like this:

 int compareTo (LocalDate otherDate) { int cmp = (year - otherDate.year); if (cmp == 0) { cmp = (month - otherDate.month); if (cmp == 0) { cmp = (day - otherDate.day); } } return cmp; } 

But this is a comparator for LocalDate and you need a student on this.

 int compareTo (Student otherStudent) { LocalDate otherDate = otherStudent.dateOfAdmission; int cmp = (year - otherDate.year); if (cmp == 0) { cmp = (month - otherDate.month); if (cmp == 0) { cmp = (day - otherDate.day); } } return cmp; } 

It will be a comparator of students, but it will be compared only by date!