Tampilkan postingan dengan label java enum. Tampilkan semua postingan
Tampilkan postingan dengan label java enum. Tampilkan semua postingan

Jumat, 30 Juli 2021

Why Enum Singleton are better in Java? Examples

Why Enum Singleton are better in Java? Examples

Enum Singletons are new way to implement Singleton pattern in Java by using Enum with just one instance. Though Singleton pattern in Java exists from long time Enum Singletons are relatively new concept and in practice from Java 5 onwards after introduction of Enum as keyword and feature. This article is somewhat related to my earlier post on Singleton, 10 interview questions on Singleton pattern in Java where we have discussed common questions asked on interviews about Singleton pattern and 10 Java enum examples, where we have seen how versatile enum can be. This post is about why should we use Enum as Singleton in Java, What benefit it offers compared to conventional singleton methods etc.

Rabu, 28 Juli 2021

How to Compare Two Enum in Java? Equals vs == vs CompareTo Example

How to Compare Two Enum in Java? Equals vs == vs CompareTo Example

How do I compare two enum in Java? Should I use == operator or equals() method? What is difference between comparing enum with == and equals() method are some of the tricky Java questions. Until you have solid knowledge of Enum in Java, It can be difficult to answer these question with confidence. By the way unlike comparing String in Java, you can use both == and equals() method to compare Enum, they will produce same result because equals() method of Java.lang.Enum internally uses == to compare enum in Java. Since every Enum in Java implicitly extends java.lang.Enum ,and since equals() method is declared final, there is no chance of overriding equals method in user defined enum. If you are not just checking whether two enums are equal or not, and rather interested in the order of different instances of Enum, then you can use compareTo() method of enum to compare two enums.