Other methods in Enum

We know that all our enum types are converted into classes which inherit java.lang.Enum.
There are many methods defined in java.lang.Enum,

public final int ordinal()
returns the position of the enum constant in the enum list. The position is also called the ordinal value of the enum constant and it starts with 0.

Another method which returns the name of the enum constant, exactly as declared in its enum declaration is name().

public final String name()
The toString() method uses this name() method to print the name of the constant.

Hence all the below methods are equivalent,

System.out.println(enumVariable);
System.out.println(enumVariable.name());
System.out.println(enumVariable.toString());

package com.ibytecode.enums;

public class PizzaEnumOrdinal {

	enum PizzaSize {
		SMALL, MEDIUM, LARGE
	};

	public static void main(String[] args) {
		
		for(PizzaSize size : PizzaSize.values()) {
			System.out.println(size.name() + ", Position: " +
						size.ordinal());
		}
	}

}

SMALL, Position: 0
MEDIUM, Position: 1
LARGE, Position: 2

To compare two enum constants based on their ordinal values (position) we can use the compareTo() method of java.lang.Enum class. The method signature is as follows.

public final int compareTo(enum-type e)
This method returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
package com.ibytecode.enums;

public class PizzaEnumCompareTo {

	enum PizzaSize {
		SMALL, MEDIUM, LARGE
	};

	public static void main(String[] args) {
		PizzaSize s1 = PizzaSize.SMALL;
		PizzaSize s2 = PizzaSize.MEDIUM;
		PizzaSize s3 = PizzaSize.LARGE;
		
		if(s1.compareTo(s2) < 0)
			System.out.println(s1 + " is positioned before " + s2);
		if(s3.compareTo(s2) > 0)
			System.out.println(s3 + " is positioned after " + s2);
		if(s1.compareTo(s3) < 0)
			System.out.println(s1 + " is positioned before " + s3);
		
	}
}

SMALL is positioned before MEDIUM
LARGE is positioned after MEDIUM
SMALL is positioned before LARGE

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.