Java – why is enumeration more useful than HashMap in this case?

This seems to be a common problem, but all the items in the suggestion box don't accurately explain what I'm thinking In this link, everyone suggests using enumeration types (I've studied it now, but I've never used it before) I'm going to suggest simply using HashMap and reading the answers to look at enum( http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html )Is it actually a better answer According to the link on Oracle, "you should use enumeration types whenever you need to represent a set of fixed constants." So it is

My question is... Why? Is there a contract that they won't change? Is it a shorter way to get some class functions? How is the performance? Why is this just defining constants in the same class?

thank you!

Solution

Enumerated instances are objects that encapsulate data and behavior just like any other object By passing an enumerated instance, anyone can call its method For example, if you pass a map key as a string, you cannot do anything useful with that key Moreover, the code is less type safe and self - documenting, because string is likely to be completely different from what it should be

What is the most readable?

public int countDays(Set<Month> months,int year) {
    int count = 0;
    for (Month month : months) {
        count += month.getDays(year);
    }
    return count;
}

or

public int countDays(Set<String> months,int year) {
    int count = 0;
    for (String month : months) {
        int days = monthMap.get(month);
        if (month.equals(Months.FEBRUARY)) {
            days = computeDaysInFebruary(year);
        }
        count += days;
    }
    return count;
}

What if I pass something other than the month name in the collection?

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>