The principle behind using strings in JAVA7 switch statements

Source: Internet
Author: User

First look at the code and the post-compilation code:

/** * @author Doctor * * @time March 28, 2015 PM 3:26:06 */public class Stringforswitch {@Rulepublic expectedexception ex = EXP Ectedexception.none (); @Testpublic void Test_string_switch () {string result= ""; Switch ("Doctor") {case "doctor": Result = "Doctor"; break;default:break;} Assertthat (Result, Equalto ("Doctor")); }

Post-compilation Code:

public class stringforswitch {     @Rule     public  Expectedexception ex = expectedexception.none ();    public  Stringforswitch ()  {    }     @Test     public  void test_string_switch ()  {        string result  =  "";        string var2 =  "Doctor";         switch ("Doctor". Hashcode ())  {         case -1326477025:             if (Var2.equals ("Doctor"))  {                 result =  "Doctor";             }        default:             Assert.assertthat (Result, isequal.equalto ("Doctor"));         }     }}

1. The string type is implemented in a switch statement by comparing the value of hashcode with the content of the string.

2. Because the hash value of a string may be duplicated, the hash function is poorly designed. It is also necessary to further compare the contents of the string.

3. Compiler-level syntax sugar just doesn't change,switch is a comparison of integers.

4. JDK1.8.0_40 environment.

The principle behind using strings in JAVA7 switch statements

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.