[JAVA] Basic usage of enums and code examples

Introduction

The enum is called an enumeration, and it seems to be an excellent one that can group several constants together. Since I studied hard, I will summarize it for personal use while practicing article writing. The goal was an article that you can glance at and check when you think, "How do you use this?" In this article, we will only deal with the basic usage of enumeration types, so we will not mention internal processing.

Enumeration features

--Multiple constants (enumerators) can be unified and managed by one type --Multiple expressions can be defined in one enumerator --Common processing can be defined for enumerators

The point is that you can manage constants collectively. However, it is necessary to rewrite the code every time the constant is changed. Before implementing it, consider whether it really should be defined as an enum.

Enumeration type definition

This section introduces the definition of enumeration type. Here's a very simple code example:

Code example


public enum Fruit {		//"class" ⇒ "enum"Rewrite to
	//Enumerator definition
	APPLE,
	ORANGE,
	PEACH;
}

public class Basket {
	public static void main(String[] args) {

		Fruit flt = Fruit.ORANGE;				//get enum
		System.out.println( flt.toString() );	//ORANGE
	}
}

An enum with one of the set constants (enumerator) can be held as a variable and obtained as needed. In the above example, ʻAPPLE, ORANGE, PEACH are input as constants, so there is no concern that other character strings (GRAPE`, etc.) will be output. In this way, it is a feature and merit of enum that it can handle only predefined constants.

Enumerators can also be defined by combining multiple primitive and class types. The following is an example.

Code example

public enum Fruit {

	APPLE("Apple", 1),
	ORANGE("Orange", 2),
	PEACH("Peaches", 3);
	
	private String label;
	private int id;


	private Fruit(String label, int id) {	//Constructor declared private
		this.label = label;
		this.id = id;
	}


	public String getLabel() {
		return label;
	}

	public int getId() {
		return id;
	}
}

public class Basket {

	public static void main(String[] args) {

		Fruit flt = Fruit.APPLE;
		System.out.println( flt.getLabel() );		//Apple

		System.out.println( Fruit.PEACH.getId() );	//3
	}
}

In the above example, the enumerator is a combination of a string and an integer. If you compare the Fruit class and the Basket class, you can see that they are getting the corresponding values respectively.

In order to define and operate enumerators in combination, it is necessary to define fields, constructors, and methods respectively. Conversely, you can define fields, constructors, and methods as needed.

An example of defining a simple method is shown below.

Code example

public enum Fruit {

	APPLE("Apple", 1),
	ORANGE("Orange", 2),
	PEACH("Peaches", 3);

	private String label;
	private int id;


	private Fruit(String label, int id) {
		this.label = label;
		this.id = id;
	}


	public String getLabel() {
		return label;
	}

	public int getId() {
		return id;
	}


	public static Fruit getById(int id) {

		for( Fruit flt : Fruit.values() ) {	//Scanning with extended for statement
			if( flt.getId() == id ) {
				return flt;					//Returns instances that match the criteria
			}
		}
		return null;
	}
}

public class Basket {

	public static void main(String[] args) {

		Fruit flt = Fruit.getById(2);
		System.out.println( flt.getLabel() );	//Orange
	}
}

Depending on the method, it is not always necessary to define it in the enum class (for example, the getById method in the above example can be operated without problems even if it is defined in another class), but general-purpose methods around the enumerator are summarized. Would be convenient.

Enum method

Enums come with useful methods from the beginning. Although it is described in the code example in the previous section, I will introduce it again in this section.

・ ToString ()


public class Basket {
	public static void main(String[] args) {

		Fruit flt = Fruit.ORANGE;
		System.out.println( flt.toString() );	//ORANGE
	}
}

toString () is a method to get the string declared as an enumerator. name () gives the same result, but it seems to be deprecated. The difference is that toString () can be overridden, but name () cannot.

・ ValueOf (String name)


public class Basket {

	public static void main(String[] args) {

		Fruit flt = Fruit.valueOf("PEACH");
		System.out.println( flt.getLabel() );	//Peaches
	}
}

valueOf (String name) is a method that returns an enumerator that matches the argument string. Note that if no matching enumerator exists, it will return ʻIllegalArgumentException`.

・ Values ()


public class Basket {

	public static void main(String[] args) {

		for( Fruit flt : Fruit.values() ) {
			System.out.println( flt.getLabel() );	//Apple
													//Orange
													//Peaches
		}
	}
}

values () is a method mainly used in extended for statements. As in the above example, the enumerator can be processed comprehensively.

At the end

I wrote a Qiita article for the first time this time, but I realized that I lacked knowledge. Also, I checked the unclear points by looking at the materials here and there, but I also understood that I would forget the place I saw properly if I did not record it. I would like to continue writing articles as a personal summary.

Reference material

About enum (Qiita article) Behavior with Enum (Qiita article)

Recommended Posts

Basic usage of enums and code examples
Introduction and basic usage of Simple Calendar gem
Super basic usage of Eclipse
Basic usage of java Optional Part 1
[Rails] Differences and usage of each_with_index and each.with_index
Basic structure of Java source code
Examples of lambda, sort, and anonymous functions
[Ruby] Classification and usage of loops in Ruby
Introduction and usage explanation of Font Awesome
Discrimination of Enums in Java 7 and above
JDBC promises and examples of how to write
Table of contents Code refactoring and related articles
Learn the rudimentary mechanism and usage of Gradle 4.4
JDK installation and configuration, basic source code structure
Java review ③ (Basic usage of arrays / reference type)
[Ruby] Basic code list. Keep the basics with examples
The comparison of enums is ==, and equals is good [Java]
Minimal usage of Mockito
Basic format of Dockefile
Basic operators and operations
[Ruby] Creating code using the concept of classes and instances
[Java] Difference between assignment of basic type variable and assignment of reference type variable
Sample code for basic mocking and testing with Mockito 3 + JUnit 5