English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In questo tutorial, impareremo l'enum in Java. Impareremo a creare e utilizzare enum e classi enum con l'aiuto di esempi.
In Java, un enum è un tipo che ha un insieme di valori possibili fissi. Utilizziamo la chiave enum per dichiarare un enum. Ad esempio,
enum Size { PICCOLO, MEDI, GRANDE, GRANDE {}
Qui, abbiamo creato un enum chiamato Size.
I valori all'interno delle graffe sono detti valori enum (costanti). Questi sono i valori unici che può mantenere il tipo enum.
Attenzione:Le costanti dell'enum sono solitamente rappresentate in maiuscolo.
Facciamo un esempio semplice.
enum Size { PICCOLO, MEDI, GRANDE, GRANDE {} class Main { public static void main(String[] args) { System.out.println(Size.SMALL); System.out.println(Size.MEDIUM); {} {}
Output result
SMALL MEDIUM
Dal esempio sopra, possiamo vedere che accediamo ai valori costanti utilizzando il nome dell'enum.
Allo stesso modo, possiamo creare variabili di tipo enum. Ad esempio,
Size pizzaSize;
In questo caso, pizzaSize è una variabile di tipo Size. Può assegnare solo 4 valori.
pizzaSize = Size.SMALL; pizzaSize = Size.MEDIUM; pizzaSize = Size.LARGE; pizzaSize = Size.EXTRALARGE;
enum Size { PICCOLO, MEDI, GRANDE, GRANDE {} class Test { Size pizzaSize; public Test(Size pizzaSize) { this.pizzaSize = pizzaSize; {} public void orderPizza() { switch(pizzaSize) { case SMALL: System.out.println("Ho ordinato una pizza piccola."); break; case MEDIUM: System.out.println("Ho ordinato una pizza di media grandezza."); break; default: System.out.println("Non so quale ordinare."); break; {} {} {} class Main { public static void main(String[] args) { Test t1 = new Test(Size.MEDIUM); t1.orderPizza(); {} {}
Output result
Ho ordinato una pizza di media grandezza.
Nel programma sopra, abbiamo creato un tipo enum Size. Poi, abbiamo dichiarato una variabile di tipo Size chiamata pizzaSize.
La variabile pizzaSize può assegnare solo 4 valori (SMALL, MEDIUM, LARGE, EXTRALARGE).
La variabile pizzaSize assegna il costante MEDIUM. Sulla base di questo, verrà stampata una situazione della语句 switch case.
In Java, il tipo enum è considerato un tipo speciale di classe. È stato introdotto nella versione Java 5.
Una classe enum può contenere metodi e campi come una classe regolare.
enum Size { constant1, constant2, …, constantN; // metodi e campi {}
Le costanti enum sono sempre public static final.
Quando si crea una classe enum, il compilatore crea anche un'istanza (oggetto) per ogni costante enum.
enum Size{ SMALL, MEDIUM, LARGE, EXTRALARGE; public String getSize() { // questo si riferisce all'oggetto SMALL switch(this) { case SMALL: return "small"; case MEDIUM: return "medium"; case LARGE: return "large"; case EXTRALARGE: return "extra large"; default: return null; {} {} public static void main(String[] args) { //Using the SMALL object to call the getSize() method System.out.println("The size of the pizza is " + Size.SMALL.getSize()); {} {}
Output result
The size of the pizza is small
In the above example, we created an enum class Size. It has four constants SMALL, MEDIUM, LARGE, and EXTRALARGE.
Since Size is an enum class, the compiler will automatically create an instance for each enum constant.
Inside the main() method, we have used the instance SMALL to call the getSize() method.
Like a regular class, the enum class can also contain a constructor. For more information, please visitCostruttori di enum Java.
There are some predefined methods in the enum class that can be used at any time.
The ordinal() method returns the position of the enum constant. For example,
ordinal(SMALL) //returns 0
The compareTo() method compares enum constants based on their ordinal values. For example,
Size.SMALL.compareTo(Size.MEDIUM) //returns ordinal(SMALL) - ordinal(MEDIUM)
The toString() method returns the string representation of the enum constant. For example,
SMALL.toString() //returns "SMALL"
The name() method returns the definition name of the enum constant in string form. The value returned by the name() method is final. For example,
name(SMALL) //returns "SMALL"
The valueOf() method takes a string and returns the enum constant with the same string name. For example,
Size.valueOf("SMALL") //returns SMALL
The values() method returns an array of enum types containing all enum constants. For example,
Size[] enumArray = Size.value();
In Java, enum has been introduced to replace the use of int constants.
Supponiamo di aver utilizzato un insieme di costanti intere.
class Size { public final static int SMALL = 1; public final static int MEDIUM = 2; public final static int LARGE = 3; public final static int EXTRALARGE = 4; {}
Qui, se stampiamo la costante, si verifica un problema. Questo perché stampa solo numeri, il che potrebbe non essere utile.
Quindi, possiamo semplicemente usare l'enum, al posto di usare costanti intere. Ad esempio,
enum Size { PICCOLO, MEDI, GRANDE, GRANDE {}
Questo rende il nostro codice più intuitivo.
Allo stesso modo, l'enum offre la sicurezza del tipo a compile-time.
Se dichiariamo una variabile di tipo Size (come nell'esempio sopra), possiamo garantire che la variabile conterrà uno dei quattro valori. Se tentiamo di passare un valore diverso da questi quattro, il compilatore genererà un errore.