Friday, 2 May 2014

Enum : compareTo : Compare two enum constants

public final int compareTo(E o)
Returns a negative integer, zero, or a positive integer as this object is less
than, equal to, or greater than the specified object.

enum Day{
 MON,
 TUE,
 WED,
 THU,
 FRI,
 SAT,
 SUN;
 
 public static void main(String args[]){
  System.out.println("\tMON\tTUE\tWED\tTHU\tFRI\tSAT\tSUN");
  
  for(Day d1 : Day.values()){
   System.out.print(d1 +"\t");
   for(Day d2 : Day.values()){
    System.out.print(d1.compareTo(d2)+" \t");
   }
   System.out.println();
  }
 }
}

Output
        MON     TUE     WED     THU     FRI     SAT     SUN
MON     0       -1      -2      -3      -4      -5      -6
TUE     1       0       -1      -2      -3      -4      -5
WED     2       1       0       -1      -2      -3      -4
THU     3       2       1       0       -1      -2      -3
FRI     4       3       2       1       0       -1      -2
SAT     5       4       3       2       1       0       -1
SUN     6       5       4       3       2       1       0




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment