Java enumeration: overwrite toString, and then read equals and hashCode.

Source: Internet
Author: User

Still using Java enumeration: Understanding enumeration examples. Slightly modified.


[Java]
Package mark. demo;
 
Public class EnumDemo {
 
Public static void main (String [] args ){
For (Color color: Color. values ()){
System. out. println (color );
}
}
 
Public enum Color {
RED ("red color", 0), GREEN ("green color", 1), BLUE ("blue color", 2), YELLOW (
"Yellow color", 3 );
 
Color (String name, int id ){
_ Name = name;
_ Id = id;
}
 
Private String _ name;
Private int _ id;
 
Public String getName (){
Return _ name;
}
 
Public int getId (){
Return _ id;
}
}
 
}

Print results

 


I thought it would print the following format

 

 

However, this is not the case. For details, see the source code of Enum and the toString method:


[Java]
/**
* Returns the name of this enum constant, as contained in
* Declaration. This method may be overridden, though it typically
* Isn' t necessary or desirable. An enum type shocould override this
* Method when a more "programmer-friendly" string form exists.
*
* @ Return the name of this enum constant
*/
Public String toString (){
Turn name;
}

Note: the name of enum constant (name of the enumerated constant Value) is returned ).


If we want to get the expected results, we need to rewrite the toString method.


[Java]
Package mark. demo;
 
Public class EnumDemo {
 
Public static void main (String [] args ){
For (Color color: Color. values ()){
System. out. println (color );
}
}
 
Public enum Color {
RED ("red color", 0), GREEN ("green color", 1), BLUE ("blue color", 2), YELLOW (
"Yellow color", 3 );
 
Color (String name, int id ){
_ Name = name;
_ Id = id;
}
 
Private String _ name;
Private int _ id;
 
Public String getName (){
Return _ name;
}
 
Public int getId (){
Return _ id;
}

@ Override
Public String toString (){
Return _ name + "," + _ id;
}
}
}

In the code above, the enhanced for loop is used to call the values () method to traverse the enumerated values. You can also traverse the values as follows:

[Java]
For (Color color: Color. values ()){
System. out. println (color. getName () + "," + color. getId ());
}

 


Equals and hashCode methods of the Enum class


[Java]
/**
* Returns true if the specified object is equal to this
* Enum constant.
*
* @ Param other the object to be compared for equality with this object.
* @ Return true if the specified object is equal to this
* Enum constant.
*/
Public final boolean equals (Object other ){
Return this = other;
}
 
/**
* Returns a hash code for this enum constant.
*
* @ Return a hash code for this enum constant.
*/
Public final int hashCode (){
Return super. hashCode ();
}

They are all final. Obviously, designers do not want subclass to rewrite these two methods.


Indeed, the two methods cannot be rewritten in enumeration. But how to use this method?

Now, we will not rewrite the toString method to see the equals effect.


[Java]
Public enum Color {
RED ("red color", 0), GREEN ("green color", 1 ),
BLUE ("blue color", 2), YELLOW ("yellow color", 3 );
 
Color (String name, int id ){
_ Name = name;
_ Id = id;
}
 
Private String _ name;
Private int _ id;
 
Public String getName (){
Return _ name;
}
 
Public int getId (){
Return _ id;
}
}


Test results:

[Java]
Public static void main (String [] args ){
System. out. println (Color. RED. equals (""); // false
System. out. println (Color. RED. equals ("red color"); // false
System. out. println (Color. RED. equals ("RED"); // false
System. out. println (Color. RED. equals (Color. BLUE); // false
// Same object
System. out. println (Color. RED. equals (Color. RED); // true
// Actually two strings
System. out. println (Color. RED. toString (). equals ("RED"); // true
// Actually two strings
System. out. println (Color. RED. getName (). equals ("red color"); // true
// HashCode
System. out. println ("Color. RED. hashCode =" + Color. RED. hashCode ());
}

If you overwrite the toString method

[Java] view plaincopyprint?
System. out. println (Color. RED. toString (). equals ("RED "));


The returned value may be true or false, depending on your toString implementation.
 
As shown in the following implementation method: return the capital form of _ name.


[Java]
@ Override
Public String toString (){
Return this. _ name. toUpperCase ();
}


To sum up, we recommend that you rewrite the toString method as needed and make good use of the equals method.

 

 

 

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.