Source of Direction.java


  1: 
  2: package maze; 
  3: 
  4: /*
  5:  *  An enumeration type 
  6:  */ 
  7: public class Direction implements Comparable { 
  8: 
  9:   public static final Direction NORTH = new Direction("North");
 10:   public static final Direction EAST  = new Direction("East");
 11:   public static final Direction SOUTH = new Direction("South");
 12:   public static final Direction WEST  = new Direction("West");
 13: 
 14:   public String toString() { 
 15:     return name; 
 16:   }
 17: 
 18:   public int getOrdinal() { 
 19:     return ordinal;
 20:   }
 21: 
 22:   public int compareTo(Object o) { 
 23:     if (o instanceof Direction) { 
 24:       return ordinal - ((Direction) o).getOrdinal();
 25:     }
 26:     return 0;
 27:   }
 28: 
 29:   public static Direction first() { 
 30:     return values[0]; 
 31:   }
 32: 
 33:   public Direction next() { 
 34:     if (ordinal < values.length - 1) { 
 35:       return values[ordinal + 1]; 
 36:     } else { 
 37:       return null; 
 38:     }
 39:   }
 40: 
 41:   public Direction opposite() { 
 42:     return values[(ordinal + 2) % 4]; 
 43:   }
 44: 
 45:   /* 
 46:   public static Direction first() { 
 47:     return NORTH; 
 48:   }
 49: 
 50:   public Direction next() { 
 51:     if (this == NORTH) { 
 52:       return EAST; 
 53:     } else if (this == EAST) { 
 54:       return SOUTH; 
 55:     } else if (this == SOUTH) { 
 56:       return WEST; 
 57:     } else if (this == WEST) { 
 58:       return null; 
 59:     }
 60:     return null;
 61:   }
 62: 
 63:   public Direction opposite() { 
 64:     if (this == NORTH) { 
 65:       return SOUTH; 
 66:     } else if (this == EAST) { 
 67:       return WEST; 
 68:     } else if (this == SOUTH) { 
 69:       return NORTH; 
 70:     } else if (this == WEST) { 
 71:       return EAST; 
 72:     }
 73:     return null;
 74:   }
 75:   */ 
 76:  
 77:   private Direction(String name) { 
 78:     this.name = name; 
 79:   }
 80:   
 81:   private static int nextOrdinal = 0;  
 82:   private final String name; 
 83:   private final int ordinal = nextOrdinal++; 
 84: 
 85:   private static final Direction[] values = { NORTH, EAST, SOUTH, WEST }; 
 86: 
 87: }