Java Reference
In-Depth Information
The code in Listing 18-6 demonstrates the use of the new features added to the SuperSmartSeverity enum type.
Listing 18-6. A Test Class to Test the SuperSmartSeverity Enum Type
// SuperSmartSeverityTest.java
package com.jdojo.enums;
public class SuperSmartSeverityTest {
public static void main(String[] args) {
for(SuperSmartSeverity s : SuperSmartSeverity.values()) {
String name = s.name();
String desc = s.toString();
int ordinal = s.ordinal();
int projectedTurnaroundDays =
s.getProjectedTurnaroundDays();
double projectedCost = s.getProjectedCost();
System.out.println("name=" + name +
", description=" + desc +
", ordinal=" + ordinal +
", turnaround days=" +
projectedTurnaroundDays +
", projected cost=" + projectedCost);
}
}
}
name=LOW, description=Low Priority, ordinal=0, turnaround days=30, projected cost=1000.0
name=MEDIUM, description=Medium Priority, ordinal=1, turnaround days=15, projected cost=2000.0
name=HIGH, description=High Priority, ordinal=2, turnaround days=7, projected cost=3000.0
name=URGENT, description=Urgent Priority, ordinal=3, turnaround days=1, projected cost=5000.0
Comparing Two Enum Constants
You can compare two enum constants in three ways:
Using the
compareTo() method of the Enum class
Using the
equals() method of the Enum class
== operator
The compareTo() method of the Enum class lets you compare two enum constants of the same enum type.
It returns the difference in ordinal for the two enum constants. If both enum constants are the same, it returns
zero. The following snippet of code will print -3 because the difference of the ordinals for LOW(ordinal=0) and
URGENT(ordinal=3) is -3. A negative value means the constant being compared occurs before the one being
compared against.
Using the
Severity s1 = Severity.LOW;
Severity s2 = Severity.URGENT;
int diff = s1.compareTo(s2);
System.out.println(diff);
 
Search WWH ::




Custom Search