简体   繁体   中英

How can I change the value of an enum variable in a different class?

I am currently working on a project that asks me to sort a collection of songs. I am using the solution presented in this question to accomplish this, while modifying it slightly: Sorting a collection of objects

import java.util.Comparator;

public class SongComparator implements Comparator<Song> {
    public enum Order {
        YEAR_SORT, RANK_SORT, ARTIST_SORT, TITLE_SORT
    }

    public Order sortingBy;

    @Override
    public int compare(Song song1, Song song2) {
        switch (sortingBy) {
        case YEAR_SORT:
            return Integer.compare(song1.year, song2.year);
        case RANK_SORT:
            return Integer.compare(song1.rank, song2.rank);
        case ARTIST_SORT:
            return song1.artist.compareTo(song2.artist);
        case TITLE_SORT:
            return song1.title.compareTo(song2.title);
        }
        throw new RuntimeException(
                "Practically unreachable code, can't be thrown");
    }

    public void setSortingBy(Order sortBy) {
            this.sortingBy = sortingBy;
    } 
}

Example sort method:

public void sortTitle() {
    SongComparator comparator = new SongComparator();
    SongComparator.Order sortingBy = SongComparator.Order.TITLE_SORT;

      Collections.sort(songs2, comparator);
    }

I want to be able to change the sortingBy variable when each respective sortField method is run, so that way it will run the right compare method. However, the way that I'm defining it in the method is just making a new sortingBy variable without changing the one in the SongComparator class at all.

You haven't set the sortingBy field of the comparator:

comparator.setSortingBy(sortingBy);
Collections.sort(songs2, comparator);

You'd better pass this value as a constructor parameter, to make sure the comparator is always in a valid state, and that you don't reproduce the bug:

SongComparator comparator = new SongComparator(SongComparator.Order.TITLE_SORT);
Collections.sort(songs2, comparator);

The sortingBy field shouldn't be public, by the way, and there should be no setter for the sortingBy field.

To make the class easier and friendlier to use, I would create factory methods:

public static SongComparator byTitle() {
    return new SongComparator(SongComparator.Order.TITLE_SORT);
}

public static SongComparator byYear() {
    return new SongComparator(SongComparator.Order.YEAR_SORT);
}
...

So that the code in the callers become:

Collections.sort(songs2, SongComparator.byTitle());

Note that with Java 8, this comparator class becomes unnecessary. You can simply use

Collections.sort(songs2, Comparator.comparing(Song::getTitle));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM