Compare Enums

Hi,

compareTo method is declared as final in Enums so you cannot override it. The default compareTo method is comparing the ordinals ( the order they are defined ) in the Enum. If you want to compare your enums based on name what you can do is, writing your own comparator and use it. For example:

public enum Category {
Technology,
Banking,

....

}

public class CategoryComparator implements Comparator<Category> {

public int compare(Category o1, Category o2) {
Collator collator = Collator.getInstance(new Locale("tr"));
return collator.compare(o1.name(), o2.name());
}
}

and use it in your sort method like :

Collections.sort(categories,new CategoryComparator());

and that is it.

if you want to know why I used Collator to compare check here

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s