6. Enumeration
Enumeration allows you to specify a group of objects, for example:
Statement:
Public enum Direction {North, East, West, South };
Usage:
Direction wall = Direction. North;
This is really an elegant concept. This is why C # decides to keep them, but why does Java choose to abandon them? In Java, you have to do this:
Statement:
Public class Direction
{
Public final static int NORTH = 1;
Public final static int EAST = 2;
Public final static int WEST = 3;
Public final static int SOUTH = 4;
}
Usage:
Int wall = Direction. NORTH;
It seems that Java is more expressive, but this is not the case. It is not type-safe. You may accidentally assign any int value to wall, and the compiler will not complain: direction wall = Direction. NORTH ;].
Frankly speaking, in my Java programming experience, I have never spent too much time writing additional things to catch errors because of this non-type security. However, it is fast to have enumeration. C # brings you a surprise: When you debug a program, if you set a breakpoint where you are using enumeration variables, the debugger will automatically translate direction and give you a readable information, instead of a numeric value that you have to translate:
Statement:
Public enum Direction {North = 1, East = 2, West = 4, South = 8 };
Usage:
Direction direction = Direction. North | Direction. West;
If (direction & Direction. North )! = 0)
//....
If you set a breakpoint on the if statement, you will get a readable direction instead of a value 5.
Note:
Statement:
Public enum Direction {North = 1, East = 2, West = 4, South = 8, Middle = 5/* pay attention to the code here */};
Usage:
Direction direction = Direction. North | Direction. West;
If (direction & Direction. North )! = 0)
//....
If you set a breakpoint on the if statement, you will get a readable ction (that is, Middle) instead of a value 5]
[Note: The reason why enumeration is discarded by Java is very likely because it can be replaced by classes. As I mentioned above, using classes alone cannot better express a feature as with other concepts. What are the advantages of Java's philosophy of "if it can be processed using classes, it will not introduce a new structure? It seems that the biggest advantage is simplicity-a short learning curve, and there is no need for programmers to consider multiple ways to do the same thing. In fact, the Java language aims to simplify C ++ in many aspects, such as no pointers, no header files, and a single object hierarchy. All of these simplification commonalities are that they actually make programming simple. However, without the enumeration, attributes, and events we just mentioned, your code becomes more complicated]