This article is participating in the Java Topic Month – Java Debug Notes event. See the event link for details

Compare Java enumeration members: == or equals ()?

I know that Java enumerations are compiled into classes with private constructors and a bunch of public static members. I always use.equals() when comparing two members of a given enumeration, for example

public useEnums(SomeEnum a) { if(a.equals(SomeEnum.SOME_ENUM_VALUE)) { ... }... }Copy the code

However, I came across some code that used the equals operator == instead of.equals () :

public useEnums2(SomeEnum a) { if(a == SomeEnum.SOME_ENUM_VALUE) { ... }... }Copy the code

Which operator should I use?

High score answer:


A lot of knowledge, really need to write out will master ! ! !   \color{purple} {~}

Is enum possible?

Yes: enumerations have strict instance controls that can be == used to compare instances. This is the language specification

The article translated from am2dgbqfb6mk75jcyanzabc67y ac4c6men2g7xr2a – stackoverflow – com. Translate. Goog/questions / 1…

The authors suggest that the same enumeration values can be compared, but pay attention to the difference between == and equals

Because a lot of students are asking, I’m going to post a nested enumeration code here: How do I get an enumeration value from a string value in Java?

Public enum SaasApiEnum {/** * Enterprise creation */ ORG_CREATE(" enterprise creation ", saasapi.org_create),; SaasApiEnum(String name, String api) { this.name = name; this.api = api; } /** * Interface name */ Private final String name; /** * private final String API; / / private static final Map<String, SaasApiEnum> MAPPINGS = new HashMap<>(64); / / Private static final Map<String, SaasApiEnum> MAPPINGS = new HashMap<>(64); / / Private static final Map<String, SaasApiEnum> MAPPINGS = new HashMap<>(64); static { for (SaasApiEnum anEnum : values()) { MAPPINGS.put(anEnum.api, anEnum); }} /** * parse the given interface address to the current enumeration type ** @param API address * @return the corresponding enumeration, or null if not found */ public static SaasApiEnum resolve(String api) { return (api ! = null ? MAPPINGS.get(api) : null); } public String getName() { return name; } public String getApi() { return api; }}Copy the code

In an enumeration we can set the property, and if the property is Interger then we might have a problem using ==.

Integer The correct comparison method is to use equals.

[-128,127] : == == == == == == == ==

private static class IntegerCache { static final int low = -128; static final int high; static final Integer cache[]; static { // high value may be configured by property int h = 127; String integerCacheHighPropValue = sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high"); if (integerCacheHighPropValue ! = null) { try { int i = parseInt(integerCacheHighPropValue); i = Math.max(i, 127); // Maximum array size is Integer.MAX_VALUE h = Math.min(i, Integer.MAX_VALUE - (-low) -1); } catch( NumberFormatException nfe) { // If the property cannot be parsed into an int, ignore it. } } high = h; cache = new Integer[(high - low) + 1]; int j = low; for(int k = 0; k < cache.length; k++) cache[k] = new Integer(j++); // range [-128, 127] must be interned (JLS7 5.1.7) assert IntegerCache. High >= 127; } private IntegerCache() {} }Copy the code

This is the static inner class of Integer. When the Integer class is loaded into memory, it performs the initialization of the static code block in its inner class. The main thing it does is to wrap the numbers between [-128,127] into the Integer class and store the corresponding references in the cache array. This creates space in the method area to store the static Integer variables, and the static cache array is also stored here for the thread to consume, also known as the static cache. We know that objects in Java are referenced, so when we initialize a variable with an Integer declaration, we first determine whether the assigned value is between -128 and 127. If so, we use the space in the static cache and return the corresponding reference to the cache array, and store it in the run stack, instead of re-opening the memory.

		Integer a =127;
		Integer b =127;
		System.out.println(a==b);  // true
		a=128;
		b=128;
		System.out.println(a==b); // false

Copy the code

Authors often use: equals.


Welcome to my column S t a c k O v e r F l o w . I will screen for good questions and answers and test them frequently during the interview ! ! !   \color{red} Welcome to my column StackOverFlow, I will filter quality q&A, interview often test!! {~}


There are the latest, elegant ways to implement it, and I’ll write my thoughts on this q&A at the end \color{red} has the latest and elegant implementation, and I’ll write my thoughts on this q&A at the end {~}

Thank you very much for reading here, if this article is good, feel something

Please like 👍 follow ❤️ share 👥 is really very useful for me with 8 pack abs!!

If there are any mistakes in this blog, please comment and comment. Thank you very much! ❤ ️ ❤ ️ ❤ ️ ❤ ️