Java. Enum class

Enum class. Enum class methods: clone(), compareTo(), getDeclaringClass(), hashCode(), name(), ordinal(), toString()

Before exploring this topic, it is recommended that you familiarize yourself with the following topic:


Contents


Search other resources:

1. Enum class. General information. An overview of the methods of the Enum class

In the Java language, all enumerations declared with the enum keyword automatically inherit from the generic Enum class. According to the documentation, the general form of declaring Enum class is as follows:

class Enum<E extends Enum<E>>

here

  • E – enumeration type.

The Enum class has no public constructors.

Below is an abbreviated list of the methods of the Enum class that are available in all enumerations:

  • clone() – calling this method prevents cloning of enums;
  • compareTo() – compares the ordinal values of two named constants of the same enumeration;
  • getDeclaringClass() – returns the type of the enumeration of which the calling constant is a member;
  • hashCode() – returns the hash code of the object;
  • name() – returns the name of the named constant;
  • ordinal() – returns the position of a constant in the list of enumeration constants;
  • toString() – returns the name of the named constant.

 

2. The сlone() method. Prevent cloning

In the Enum class, the clone() method is intended to prevent the enumeration cloning operation from being performed. This method is hidden, so it will not be possible to call it for enumeration. The clone() method declaration in the Enum class is as follows

protected final Object clone() throws CloneNotSupportedException

When you declare an enumeration and assign it a constant value, a new object is created each time. Each assigned constant is a separate, independent object, so it doesn’t make sense to clone this object, since it is already being cloned.

The following example explains this feature.

Example.

// Enumeration defining well-known time intervals
enum TimeIntervals {
  secondsInMinute(60), // number of seconds in one minute
  hoursInDay(24),     // number of hours in a day
  daysPerWeek(7),     // number of days in a week
  daysInYear(365);     // number of days in a year

  // Constructor
  TimeIntervals(int interval)
  {
    this.interval = interval;
  }

  // Internal variable storing the value of the time interval
  private int interval;

  // Access to the 'interval' value
  public int get() { return interval; }
}

public class TrainEnumerations {

  public static void main(String[] args) {
    // The clone() method - make a copy of the enumeration
    // 1. Create an instance of the TimeIntervals enumeration type
    TimeIntervals t1;

    // 2. Initialize enumeration t1 with a value
    t1 = TimeIntervals.hoursInDay;

    // 3. Create an instance of another enum and initialize it with the value t1
    TimeIntervals t2 = t1;

    // 4. Display the value of t2 enumeration
    System.out.println(t2); // hoursInDay

    // 5. Change enumeration instance t1 with a different value
    t1 = TimeIntervals.daysPerWeek;

    // 6. Re-display the value of the enumeration t2
    System.out.println(t2); // hoursInDay - the value has not changed
  }
}

The result of the program

hoursInDay
hoursInDay

As you can see from the result, when assigning enumerations

...

TimeIntervals t2 = t1;

...

the enumerations t1 and t2 point to different locations in memory. That is, the assignment of references did not take place, as is the case with class instances. This fact proves the result of outputting the value of t2 after changing the value in the enumeration t1

...

// 5. Change enumeration instance t1 with a different value
t1 = TimeIntervals.daysPerWeek;

// 6. Re-display the value of the enumeration t2
System.out.println(t2); // hoursInDay - the value has not changed

...

As you can see from the result, the value of enumeration t2 has not changed, that is, cloning is performed automatically. Therefore, it makes no sense to define a clone() method to work with enumerations.

 

3. The compareTo() method. Compare the values of two enumeration objects

The compareTo() method allows you to compare the values of two objects of the same enumeration type. According to the documentation, the method has the following declaration

public final int compareTo(E obj)

here

  • E – an enumeration type that has the current enumeration (object) and the obj enumeration. The current enumeration and the enumeration obj must be of the same type E;
  • obj is an enumeration (object) that is compared with the current enumeration. The method compares the current enumeration to a specific enumeration that is passed as a parameter to the method. Method returns:
  • a negative number if the current object is less than the specified obj. The term “less than” means that the value of the current constant (object) comes before the value of the constant obj in the enumeration;
  • zero (0), if the values of the current constant and the constant obj are equal;
  • a positive number if the value of the constant in the current enumeration comes after the value of the constant in the enumeration obj.

Example. The example compares the values of the constants from the Seasons enumeration.

// An enumeration that describes the seasons
enum Seasons {
  Winter, Spring, Summer, Autumn
}

public class TrainEnumerations {

  public static void main(String[] args) {
    // compareTo() method - compare ordinal values of constants
    // 1. Declare two enums and assign them values
    Seasons s1, s2;
    s1 = Seasons.Summer;
    s2 = Seasons.Spring;

    // 2. Implement comparison of enumerations s1 and s2
    int result;
    result = s1.compareTo(s2); // 1
    System.out.println("Seasons.Summer == Seasons.Spring => " + result);

    s1 = Seasons.Winter;
    s2 = Seasons.Winter;
    result = s2.compareTo(s1); // 0
    System.out.println("Seasons.Winter == Seasons.Winter => " + result);

    s1 = Seasons.Spring;
    s2 = Seasons.Autumn;
    result = s1.compareTo(s2); // -2
    System.out.println("Seasons.Spring == Seasons.Autumn => " + result);
  }
}

Program result

Seasons.Summer == Seasons.Spring => 1
Seasons.Winter == Seasons.Winter => 0
Seasons.Spring == Seasons.Autumn => -2

As the result shows, the compareTo() method returns the difference between the ordinal numbers of the constants of the current enumeration and the enumeration that is an input parameter of the method.

 

4. Method getDeclaringClass(). Get information about the enumeration

Using the getDeclaringClass() method, you can get comprehensive information about an enumeration (a list of constants, a list of methods, constructors in an enumeration, etc.).

According to the Java documentation, the method declaration is as follows

public final Class<E> getDeclaringClass()

here

  • E – enumeration type.

The method returns an object of the class corresponding to the enumeration type E.

Example.

The example shows how to use the getDeclaringClass() method to define some of the characteristics of the Days and Seasons enumerations.

import java.lang.reflect.Field;

// An enumeration describing the days of the week
enum Days {
  Sun, Mon, Tue, Wed, Thu, Fri, Sat
}

// An enumeration that describes the seasons
enum Seasons {
  Winter, Spring, Summer, Autumn
}

public class TrainEnumerations {

  public static void main(String[] args) {
    // getDeclaringClass() method - get the declared class
    // 1. Declare an instance of the enumeration of type Days
    Days day = Days.Mon;

    // 2. Print the name of the Days enumeration
    String nameClass = day.getDeclaringClass().getName();
    System.out.println(nameClass);

    // 3. Retrieve data for an instance of season1 of the Seasons enumeration.
    Seasons season1 = Seasons.Summer;
    Class<Seasons> classSeason1 = season1.getDeclaringClass();

    // 3.1. Display the name of the class
    System.out.println(classSeason1.getName());
    System.out.println(classSeason1.getTypeName());

    // 3.2. Print the field names from the Seasons enumeration.
    System.out.println("-----------------------------------");
    Field[] fl = classSeason1.getDeclaredFields();

    for (int i=0; i<fl.length; i++)
      System.out.println(fl[i].getName());
  }
}

Program result

Days
Seasons
Seasons
-----------------------------------
Winter
Spring
Summer
Autumn
ENUM$VALUES

 

5. Method hashCode(). Get hash code of an object

The hashCode() method returns the hash code of the object. The method has the following declaration

public final int hashCode()

Example.

// An enumeration that describes the days of the week
enum Days {
  Sun, Mon, Tue, Wed, Thu, Fri, Sat
}

public class TrainEnumerations {

  public static void main(String[] args) {
    // Method hashCode() - get the hash code of the object
    Days day = Days.Sat;
    int hCode = day.hashCode(); // 366712642
    System.out.println(hCode);
  }
}

Program result

366712642

 

6. Method name(). Get the name of a named constant

Using the name() method, you can get the name of a named constant in the list of enumeration constants. According to the Java documentation, the general form of the name() method is as follows:

public final String name()

The name() method can be used in special situations where you need to correctly obtain the exact name that will not change from release to release.

// An enumeration describing the colors
enum Colors {
  Red, Green, Blue, Yellow, Brown
}

public class TrainEnumerations {

  public static void main(String[] args) {
    // Method name() - returns the name of the named constant
    Colors color = Colors.Brown;
    String nameOfColor = color.name(); // get the name
    System.out.println(nameOfColor);
  }
}

Program result

Brown

 

7. Method ordinal(). Get the position of a constant in the enumeration

Using the ordinal() method, you can get the position of a constant in the enumeration. Positions are numbered from zero. The method declaration is as follows:

public final int ordinal()

 

Example.

// An enumeration that describes the days of the week
enum Days {
  Sun, Mon, Tue, Wed, Thu, Fri, Sat
}

public class TrainEnumerations {

  public static void main(String[] args) {
    // Method ordinal() - get the position of the constant
    Days day = Days.Wed;
    int ordNum = day.ordinal();
    System.out.println("Wed = " + ordNum);

    day = Days.Sat;
    ordNum = day.ordinal();
    System.out.println("Sat = " + ordNum);

    day = Days.Sun;
    ordNum = day.ordinal();
    System.out.println("Sun = " + ordNum);
  }
}

Program result

Wed = 3
Sat = 6
Sun = 0

 

8. Method toString(). Get the constant name in enumeration

The toString() method returns the name of the enumeration constant contained in the declaration. Optionally, the method can be overridden to get the name of the constant in a more convenient form.

According to the Java documentation, the method declaration is as follows

public String toString()

 

Example.

// An enumeration that describes the days of the week
enum Days {
  Sun, Mon, Tue, Wed, Thu, Fri, Sat
}

public class TrainEnumerations {

  public static void main(String[] args) {
    // Method toString() - get the name of the constant
    // 1. Declare the instance of the enumeration of type Days
    Days day = Days.Mon;

    // 2. Print the name of the constant from the day instance
    String name = day.toString();
    System.out.println(name);   // Mon

    // 3. Print the name of the constant from the Days type.
    name = Days.Sun.toString();
    System.out.println(name);   // Sun
  }
}

Program result

Mon
Sun

 


Related topics