2019-05-24
Using compareTo() method each time with different sorting property
源自: stackoverflow
问题

I am using the method compareTo() in order to sort an ArrayList of custom object named image, but in my application some times I need to sort the array according to specific attribute like goodMatches, and other times I need to sort the array according to another attributes or properties of the Object, but I cannot override the compareTo() methods more than one time for different sorts.

I have tried using flags attribute for Object but the problem is other attributes are of float type and I need to keep the method compareTo to return float not integer as goodMatches. Can any one help me overcoming this issue without the need of creating another object class, any help will be highly appreciated, below is my code of compareTo():

@Override
public int compareTo(image compareImg) {
    int compareMatches=((image)compareImg).getGoodMatches();      
    return compareMatches - this.goodMatches;
}
答案
1

Given the following Image class (use upper case for class names)

class Image {
    private int goodMatches;
    private float anotherProperty;

    .....

    public int getGoodMatches() {
        return goodMatches;
    }

    public float getAnotherProperty() {
        return anotherProperty;
    }
}

You can create a Comparator for each of your properties:

class GoodMatchesComparator implements Comparator<Image> {
    @Override
    public int compare(Image i1, Image i2) {
        return Integer.compare(i1.getGoodMatches(), i2.getGoodMatches());
    }
}

class AnotherPropertyComparator implements Comparator<Image> {
    @Override
    public int compare(Image i1, Image i2) {
        return Float.compare(i1.getAnotherProperty(), i2.getAnotherProperty());
    }
}

Then use the sort method on List to sort your list:

List<Image> images = new ArrayList<>();
// populate your list

// sort the list based on the goodMatches property
images.sort(new GoodMatchesComparator());

// sort the list based on the anotherProperty property
images.sort(new AnotherPropertyComparator());

If you need reverse order, you can do this way:

images.sort(new GoodMatchesComparator().reversed());
Using compareTo() method each time with different sorting property
查看原网页