Search code examples
javacomparatorcomparable

How to write a comparator for SimpleObjectProperty<Date>


I've tried the following, and neither work:

    public static Comparator<ModelDefects> sortFirstFoundDateAscending() {
        return new Comparator<ModelDefects>() {
            @Override
            public int compare(ModelDefects o1, ModelDefects o2) {
                return o1.getFirstFoundDate() - o2.getFirstFoundDate();
            }
        };
    }
    public static Comparator<ModelDefects> sortFirstFoundDateAscending() {
        return new Comparator<ModelDefects>() {
            @Override
            public int compare(ModelDefects o1, ModelDefects o2) {
                return o1.getFirstFoundDate().compareTo(o2.getFirstFoundDate());
            }
        };
    }

Also tried the < operator via an if statement. These didn't work either. Tonnes of searching online did not reveal the answer to me.

First Found Date and its methods are defined as so:

//Declaration:
    private SimpleObjectProperty<Date> firstfounddate;

//Initialisation in Constructor:
    this.firstfounddate = new SimpleObjectProperty<>();


//First Found Date
    public Object getFirstFoundDate() {
        return firstfounddate.get();
    }
    
    public void setFirstFoundDate(Date firstFoundDateArg) {
        this.firstfounddate.set(firstFoundDateArg);
    }
    
    public SimpleObjectProperty<Date> firstFoundDateProperty() {
        return firstfounddate;
    }

This is for a javafx project.

The key for me here is how to compare an Object with an Object?


Solution

  • You can't compare SimpleObjectProperty when the getter data type is set to object, and the getter shouldn't be set to object anyway.

    The SimpleObjectProperty is actually a generic: SimpleObjectProperty<T> with a data type of T. So in my case, changing the data type of the getter from Object to Date and modifying the comparator to read as so: return o1.getFirstFoundDate().compareTo(o2.getFirstFoundDate()) fixed the issue.