java enum parameter passing
The problem is particularly so, JAVA define an enum (e.g., RED, BLUE, GREEN) the object, the initial value RED, passed as a parameter to a method of, modification (modified to BLUE) objects in the enumeration process, after calling this method, the object still is RED, how to make changes to the object of an effective method, thank you
This is not acceptable, because: Java objects are instantiated in the heap, if an ordinary class instance variables , such as in the general class defined in the method of instance variables , spread method 2, since the process method 2 and instance variable corresponds to the same object instance heap, the method modifies the value of the object 2 in the example, the value 1 will follow the change. But java enumeration not like that. For example the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
As expressed in your question, the two outputs are RED. Specific reasons, we can use javap decompile about this class. The following code obtained
1 2 3 4 5 6 7 8 9 |
|
We can see the enumeration is actually a class implementation. The enumeration values are static final type of the class constants . When EnumClass this class is loaded, the virtual machine creates three instances of the variables in the heap. This may answer why the change invalid. When the main color variable method passes to process c Convert both pointing to the same address in the heap area, i.e. where Color.RED instance, then, the variable c is reassigned, the variable c is at this time point to the heap examples of the position Color.BLUE region. This assignment process color with the main variable is nothing to do, local Color.RED examples of the color main variable is pointing. Therefore, after the implementation of covert methods, main color variable method is not changed.
If you want to change it, I feel there are two ways, one is a covert method returns an enumeration want, assigned to the color in the main, another approach is to this class encapsulates a variable and then look at, pass into covert process.
希望对大家有所帮助。