In Java, the values()
method is a member of the Enum
class, which is the superclass of all enum
types. The values()
method returns an array of the enum
type's values in the order they are declared.
Here's an example of how to use the values()
method with an enum
in Java:
public enum Size { SMALL("S"), MEDIUM("M"), LARGE("L"), EXTRA_LARGE("XL"); private String abbreviation; private Size(String abbreviation) { this.abbreviation = abbreviation; } public String getAbbreviation() { return abbreviation; } public static void main(String[] args) { Size[] values = Size.values(); for (Size size : values) { System.out.println(size); } } }
In this example, the Size
enum
has four constant values: SMALL
, MEDIUM
, LARGE
, and EXTRA_LARGE
. The values()
method is called to get an array of all the enum
values, and the array is assigned to the values
variable.
The for
loop iterates over the elements of the values
array and prints each enum
value. The toString()
method is called implicitly on each enum
value, and the String
representation of the value is printed.
You can use the values()
method to get an array of the enum
type's values in the order they are declared. The values()
method is useful for iterating over all the values of an enum
type or for accessing a specific value by its position in the array.