java enum java enumeration tutorial with examples
このチュートリアルでは、JavaEnumクラスとコンストラクターについて詳しく説明します。さまざまなJavaプログラミング例を通じてEnumの使用方法を学習します。
これは特別なクラスであり、その説明は詳細に提供されます。 Java Enumクラスへの洞察は、それがサポートするメソッドのリストとともに提供されます。
このチュートリアルには、Java列挙型の概念を実装する十分なプログラムと、インタビュー中に尋ねられる可能性のあるいくつかのよくある質問が含まれています。
=> すべてのJavaトレーニングシリーズを見るには、ここをクリックしてください。
学習内容:
Java列挙型
Java列挙型は、インスタンス変数、メソッド、またはコンストラクターのリストに他なりません。これらは定数のグループです。列挙の概念はJDK5で導入されました。すべての列挙定数のデフォルトプロパティは、public、static、およびfinalです。
列挙型キーワード
列挙は、「」というキーワードを使用して作成されます。 列挙型 」。
以下に、列挙型を作成するための構文を示します。
構文:
列挙型enumerated_type_name
{{
enumerator1、enumerator2、…enumeratorN;
}
注意: 列挙型は、トップレベルのクラスまたはインターフェイス内、または静的コンテキストでのみ定義できます。メソッド内にあるべきではありません。
列挙型の例
この例では、カードと呼ばれる列挙型に属する4つの列挙型、つまりスペード、ハート、ダイアモンド、およびクラブを初期化します。
次に、これらの各列挙子を印刷してみます。
/* * created an enumeration called cards * with four enumerators. */ enum cards { spade, club, heart, diamond; } public class A { public static void main(String() args) { /* * stored each of the enumerators in the * reference variables a1,a2,a3,a4 respectively. * note that the new keyword was not used here */ cards a1 = cards.spade; cards a2 = cards.club; cards a3 = cards.heart; cards a4 = cards.diamond; System.out.println('Enumerators are: '+ a1 + ',' + a2 + ',' + a3 + ',' + a4); } }
出力:
列挙型クラス
上記の例(コメントを参照)で気付いたはずのことの1つは、 「新しいキーワード」 インスタンス化中。列挙型はクラスEnumとコンストラクターも定義しますが、新しいキーワードは使用しません。
プリミティブと同じ方法で定義された列挙子を使用できます。列挙型はジェネリッククラスであり、すべての列挙型は列挙型を継承します。
構文:
// Eは列挙型です。
クラス列挙型
Javaで列挙型を使用する方法
Javaの例を使用して、さまざまなシナリオでEnumを使用する方法を見てみましょう。
クラス内
列挙型はクラスの内部または外部(enumキーワードの例)で宣言できますが、メソッドの内部では宣言できません。ここでは、enumがクラス内でどのように宣言されるかを示します。
以下の例では 、クラス内に列挙型を作成してから、参照変数a1を使用して値または列挙型をフェッチしました。
public class A { /* * created an enumeration called cards * with four enumerators. */ enum cards { spade, club, heart, diamond; } public static void main(String() args) { /* * stored each of the enumerators in the * reference variables a1. * note that the new keyword was not used here */ cards a1 = cards.heart; System.out.println('Card is: '+ a1); } }
出力:
ループを介した列挙型の反復
ここでは、列挙型をループする方法について説明します。 4つの列挙型(クラス外)で列挙を宣言しました。次に、for eachループ(クラス内)を初期化し、列挙子の値をフェッチしようとしました。
/* * created an enumeration called games * with four enumerators. */ enum games { ludo, Chess, Badminton, Cricket; } public class A { public static void main(String() args) { /* * used forEach loop and stored the value in 'index' * and printed the value of each enumerator */ System.out.println('Using for each loop'); for (games index:games.values()) { System.out.println(index); } } }
出力:
3年間の経験のためのplsqlインタビューの質問
if-elseの場合
以下のプログラムでは、3つの異なる列挙型を使用して列挙型を作成し、指定された列挙型の1つの参照変数に列挙型を格納しました。
次に、ORで指定された2つの条件を実装したif条件チェックを開始し、これらの条件の1つが満たされた場合、if条件で指定されたステートメントを出力します。
それ以外の場合は、else条件で指定されたステートメントを出力します。
/* * created an enumeration called players * with three enumerators. */ enum players { sachin, virat, dhoni; } public class A { public static void main(String() args) { /* * stored enumerator in reference variable a1 for * contant dhoni */ players a1 = players.dhoni; /* * Started if statement with OR condition. * If any of these conditions are met then it will * print the statement specified inside if statement */ if(a1 == players.virat || a1 == players.sachin) { System.out.println('Sachin and Virat are greatest batsmen'); } /* * if none of the above condition is met then it will * print the below specified statement */ else { System.out.println('Dhoni is the best Captain'); } } }
出力:
Switchステートメントで
以下のプログラムでは、4つの列挙型を使用して列挙を作成しました。次に、列挙子の1つを参照変数に格納しました。その後、Switchステートメントを初期化し、これらの各列挙子をチェックしました。
その特定の列挙子が発生すると、特定のケースで指定されたステートメントが出力されます。
/* * created an enumeration called players * with four enumerators. */ enum players { sachin, dravid, virat, dhoni; } public class A { public static void main(String() args) { /* * stored enumerator in reference variable a1 for * contant dravid */ players a1 = players.dravid; /* * Started Switch Statement and if the element * matches with a1 then it will print the statement * specified in the case */ switch(a1) { // does not match case sachin: System.out.println('Sachin is best bastman ever'); break; // matches case dravid: System.out.println('Dravid is the best Test Batsman'); break; // does not match case virat: System.out.println('Virat is modern great'); break; // does not match case dhoni: System.out.println('Dhoni is the best captain ever'); break; } } }
出力:
列挙型フィールドとメソッド
列挙型フィールド
このセクションでは、列挙型フィールドについて詳しく説明します。 Java列挙型にフィールドを追加すると、各列挙子がこれらのフィールドを取得します。フィールド値は、列挙型のコンストラクターに割り当てる必要があります。
以下の構文では、列挙型が3つの列挙子で定義されていることがわかります。各列挙子の横に、int型のフィールドを定義しました。 (( 例えば。 –それぞれ(3)、(2)、(1))。
これは、Java列挙型にintをとるコンストラクターがあることを意味します。このコンストラクターはintフィールドを設定します。列挙子が定義されると、そのint値(その列挙子に指定された)がコンストラクターに渡されます。
構文:
public enum A { /* * calls a contructor with value * defined on the respective enumerator */ Enumerator1(3), Enumerator2(2), Enumerator3(1) /* * semicolon needed for the last enumerator * if there is a method following it. */ ; private final int constant; private A(int constant) { this.constant = constant; } }
注意: たとえば、(列挙型)フィールドについては、「 列挙型コンストラクタ 」。
列挙型メソッド
#1)name()
public final String name()–呼び出し定数の名前を返します(変更されていないか、変更されていません)。
#2)equals()
public final boolean equals(Object other)–objと呼び出し元オブジェクトが同じ定数を参照している場合はtrueを返します。
#3)toString
public String toString()–呼び出し元の定数の名前を返します。列挙型の宣言で使用されている名前と必ずしも一致するとは限りません。
#4)クローン
保護された最終オブジェクトclone()
throws CloneNotSupportedException –これは、クローンを作成しようとすると列挙型が例外をスローすることを意味します。
#5)hashCode()
public final int hashCode()–呼び出し元オブジェクトのハッシュコードを返します。
#6)finalize()
protected final void finalize()–列挙型クラスにfinalizedメソッドを含めることはできません。戻り値はありません。
#7)compareTo()
public final int compareTo(E obj)–これは列挙型を指定されたオブジェクトobjと比較します。オブジェクトが指定されたオブジェクトよりも小さい場合は、負の値を返します。このオブジェクトが指定されたオブジェクトobjより大きい場合は正を返し、指定されたobjがこのオブジェクトと等しい場合はゼロを返します。
#8)getDeclaringClass
public final Class getDeclaringClass()–呼び出し定数がメンバーである列挙型(列挙型宣言クラスとも呼ばれます)を返します。
#9)ordinal()、values()およびvalueOf()
これらのメソッドはすべてパッケージの一部です java.lang.Enum 。 ordinal()メソッドは、定数のインデックスに基づいて列挙定数の次数を返します。
values()メソッドは、列挙に存在するすべての値を返します。 valueOf(String)メソッドは、入力文字列の列挙定数を返します。指定された文字列が定数と一致しない場合、IllegalArgumentExceptionがスローされます。
以下に示すのは、同じ例(enumキーワードの例として)を使用し、3つのメソッドすべての概念を実装したプログラミング例です。
/* * created an enumeration called cards * with four enumerators. */ enum cards { spade, club, heart, diamond; } public class A { public static void main(String() args) { /* * created an array arr() which will store the * value of the constants/enumerators declared in the enumeration */ cards arr() = cards.values(); /* * used forEach loop and stored the value in 'type' * and printed the value as well as index with the help of * ordinal() method */ for (cards type:arr) { System.out.println(type + ' occurs at ' + type.ordinal()); } /* * passed heart as an input String which matches with the * constant declared in 'cards' */ System.out.println(cards.valueOf('heart')); } }
出力:
列挙型コンストラクタ
列挙型(クラスでもあるため)は、列挙型の作成中にデータを渡すコンストラクター、または列挙型定数とも呼ばれるコンストラクターをサポートします。
列挙型コンストラクターの主な特性は、それらがプライベートまたはプライベートパッケージであるということです。これは、クラス内またはパッケージ内のいずれかにアクセスできることを意味します。
以下の例を見てみましょう。ここでは、メソッドとコンストラクターの両方を利用しました。まず、5つの列挙型とフィールドを持つ「players」という名前の列挙型を作成しました。
次に、各プレーヤー、列挙子、または列挙型定数によってスコアリングされた実行数を返すコンストラクターとメソッドがあります。
その後、values()メソッドを使用してfor各ループを使用して各列挙子を格納および反復するメインクラスがあります。また、各選手の得点数のメソッドを呼び出しました。
/* * Created enumeration players with the field. * Declared a constructor and a method to return * the number of runs scored by the players. */ enum players { dravid(10889), sachin(18426), ganguly(11363), virat(11867), dhoni(10773) ; private int runs; /* * Created enumeration players with the field. * Declared a constructor and a method to return * the number of runs scored by the players. */ enum players { dravid(10889), sachin(18426), ganguly(11363), virat(11867), dhoni(10773) ; private int runs; players(int r) { runs = r; } int getRuns() { return runs; } } /* * Used values() method to get the enumerators and a for each loop * to get the number of runs scored by each player */ public class A { public static void main(String args()) { for (players a : players.values()) System.out.println(a + ' has scored ' + a.getRuns() + ' ODI runs'); } }
出力:
よくある質問
Q#1)Javaのイテレータと列挙型の違いは何ですか?
回答: 以下に示すのは、イテレータと列挙の違いです。
イテレータ | 列挙 |
---|---|
これは、要素を反復処理するために使用される汎用カーソルであり、すべてのコレクションクラスに適用できます。 | Enumなどのレガシークラスにのみ適用できるため、汎用カーソルではありません。コレクションクラスの読み取り権限のみ。 |
いくつかのメソッドは、反復用のhasNext()、next()です。 | いくつかのメソッドは、反復用のhasMoreElements()、nextElement()です。 |
イテレータを使用して、コレクション内の要素を削除できます。 | コレクション内の要素は読み取り権限しかないため、列挙型を使用して削除することはできません。 |
Q#2)Enumはどのように継承をサポートしますか?
回答: 結局のところ、EnumはJavaのクラスでもあるため、OOPSの基本原則である継承をサポートする必要があります。すべての列挙型はjava.lang.Enumクラスを拡張します。クラスは単一の親しか拡張できないため、Enumクラスは他の親を拡張しません。
Enumクラス(Enumメソッドのセクションで説明)の一部であるtoString()は、java.lang.Enumクラスでオーバーライドされます。
結論
このチュートリアルでは、列挙型、列挙型、Java Enumクラス、およびenumキーワードについて、必要に応じて適切な例と説明とともに説明しました。また、列挙型フィールドを持つEnumクラスに関連付けられている重要なメソッドについての洞察を提供しました。
コンストラクター、if-else、switch、およびloopsを含む列挙型への洞察が提供されています。
=> ゼロからJavaを学ぶには、ここにアクセスしてください。