The comparison of enums is ==, and equals is good [Java]

Reason

-[== does not generate NullPointerException / equals occurs](# does not generate nullpointerexception-equals occurs) -[== is lean because there is no type conversion (fast) / equals is wasteful because there is type conversion to Object type (slow)](# is lean because there is no type conversion fast-equals is There is waste because there is a type conversion to the object type. Slow) -[== has type checking at compile time / equals has no type checking](# has type checking at compile time-equals has no type checking)

== does not raise NullPointerException / equals does

Nullpo confirmation


public class EnumNullPointerExceptionTest {

	enum Season { SPRING, SUMMER, AUTUMN, WINTER; }

	public static void main(String[] args) {
		Season season = null;
		if (season != Season.SPRING) {
			System.out.println("The season is not spring.");
		}

		if (!season.equals(Season.SPRING)) {
			System.out.println("The season is not spring.");
		}
	}
}

Execution result


The season is not spring.
Exception in thread "main" java.lang.NullPointerException
	at EnumNullPointerExceptionTest.main(EnumNullPointerExceptionTest.java:13)

== passed and was angry with Nullpo at equals (although I actually passed! =).

NullPointerException does not occur == Tsuyotsuyo: blush: NullPointerException occurs equlas Yowayowa: sweat:

== is lean (fast) because there is no type conversion / equals is wasteful (slow) because there is type conversion to Object type

==Processing time measurement


public class EnumSpeedTest1 {

	enum Season { SPRING, SUMMER, AUTUMN, WINTER; }

	public static void main(String[] args) {
		Season season = Season.SPRING;

		long startTimeMs = System.currentTimeMillis();
		for (int i = 0; i < 2000000000; i++) {
			if (season == Season.SPRING) {}
		}
		long executionTimeMs = System.currentTimeMillis() - startTimeMs;
		System.out.println("How long did it take to repeat the comparison 2 billion times?" + executionTimeMs + "Milliseconds");
	}
}

==Execution result of


It took 2 milliseconds to repeat the comparison 2 billion times

Equals processing time measurement


public class EnumSpeedTest2 {

	enum Season { SPRING, SUMMER, AUTUMN, WINTER; }

	public static void main(String[] args) {
		Season season = Season.SPRING;

		long startTimeMs = System.currentTimeMillis();
		for (int i = 0; i < 2000000000; i++) {
			if (season.equals(Season.SPRING)) {}
		}
		long executionTimeMs = System.currentTimeMillis() - startTimeMs;
		System.out.println("How long did it take to repeat the comparison 2 billion times?" + executionTimeMs + "Milliseconds");
	}
}

Execution result of equals


It took 4 milliseconds to repeat the comparison 2 billion times

It's a little, but == is faster because it doesn't convert.

No type conversion and no waste == Tsuyotsuyo: relaxed: Equals that requires type conversion and is wasteful: sweat:

== has type checking at compile time / equals has no type checking

Compile confirmation


public class EnumCompileTest {

	enum Season { SPRING, SUMMER, AUTUMN, WINTER; }
	enum Color { RED, GREEN, BLUE; }
	enum Animal { DOG, CAT; }

	public static void main(String[] args) {
		if (Season.SPRING.equals(Color.RED)) {}
		if (Season.SPRING == Animal.CAT) {}
	}
}

Compile result


$ javac EnumCompileTest.java
EnumCompileTest.java:10:error:Types Season and Animal cannot be compared
		if (Season.SPRING == Animal.CAT) {}
		                  ^
1 error

The comparison of different types == was angry.

There is a type check at compile time == Tsuyotsuyo: relaxed: Equals without type checking at compile time: sweat:

Extra: Why can enums be compared with ==?

The language specification says: 8.9.1. Enum Constants

Because there is only one instance of each enum constant, it is permitted to use the == operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant.

There is only one instance of each enum constant The enum instance is a singleton. So you can compare with ==.

reference

Recommended Posts

The comparison of enums is ==, and equals is good [Java]
[Java / Swift] Comparison of Java Interface and Swift Protocol
Discrimination of Enums in Java 7 and above
The story of low-level string comparison in Java
The order of Java method modifiers is fixed
[Java] The confusing part of String and StringBuilder
I compared the characteristics of Java and .NET
[Java] String comparison and && and ||
[Java] Is it unnecessary to check "identity" in the implementation of the equals () method?
Please note the division (division) of java kotlin Int and Int
Organizing the current state of Java and considering the future
Java language from the perspective of Kotlin and C #
[JAVA] What is the difference between interface and abstract? ?? ??
[Java] About Objects.equals () and Review of String comparisons (== and equals)
I summarized the types and basics of Java exceptions
Equivalence comparison of Java wrapper classes and primitive types
What is the difference between Java EE and Jakarta EE?
[Java] Difference between == and equals
[Java] HashCode and equals overrides
Advantages and disadvantages of Java
Java is the 5th day
[Note] Java Output of the sum of odd and even elements
I tried to summarize the basics of kotlin and java
[Java] Comparison method of character strings and comparison method using regular expressions
What is the LocalDateTime class? [Java beginner] -Date and time class-
Command to check the number and status of Java threads
Java beginners briefly summarized the behavior of Array and ArrayList
Recommendation of set operation by Java (and understanding of equals and hashCode)
[Java] Note the case where equals is false but == is ture.
[Java] com.sun.glass.WindowEvent is imported and the window does not close
Java: The problem of which is faster, stream or loop
[Java] I thought about the merits and uses of "interface"
[Java] Speed comparison of string concatenation
[Java] Delete the elements of List
Comparison of WEB application development with Rails and Java Servlet + JSP
[Java] Various summaries attached to the heads of classes and members
Why the width of the full screen element is 100% and the height is 100vh
'% 02d' What is the percentage of% 2?
About fastqc of Biocontainers and Java
[Java] Get the dates of the past Monday and Sunday in order
Android --Is the order of serial processing and parallel processing of AsyncTask guaranteed? ??
[Java version] The story of serialization
About the equals () and hashcode () methods
What kind of StringUtil is good
Where is the Java LocalDateTime.now () timezone?
The design concept of Java's Date and Time API is interesting
Java comparison using the compareTo () method
[Java beginner] == operator and equals method
This and that of the JDK
The milliseconds to set in /lib/calendars.properties of Java jre is UTC
Read the first 4 bytes of the Java class file and output CAFEBABE
[Java] Judgment of identity and equivalence
Understanding equals and hashCode in Java
From fledgling Java (3 years) to Node.js (4 years). And the impression of returning to Java
I tried to summarize the methods of Java String and StringBuilder
Comparison of processing times based on awk, shell command, and Java
[Java] What is the difference between form, entity and dto? [Bean]
[Java] Correct comparison of String type
Is the version of Elasticsearch you are using compatible with Java 11?
The origin of Java lambda expressions
Investigation method when the CPU of the server running java is heavy