Java-switch expression uses the String type to achieve the purpose of Branch

Source: Internet
Author: User

As we all know, in Java, the expression in the switch statement must be an integer or operator type. strings are used for branching and can only be opportunistic.

 

The first key is to use the String hasCode to obtain the String hash code. The hash code algorithm is as follows:

S [0] * 31 ^ (n-1) + s [1] * 31 ^ (n-2) +... + s [n-1]

Therefore, the hash codes of two different strings are almost different (they may be the same. If you need to study them in depth, study it yourself, huh, huh ),

HasCode returns an int value. OK. We will use this as the constant value after case.

 

The second key is that this hasCode cannot be used directly. You can only manually obtain the string hash code in advance, declare a final int variable, and use this as a case.

 

In this way, the expression after your switch can use XXX. hasCode, And the defined constant value is used in case.

 

Isn't it a little troublesome? No way. It can only be achieved in a single bend.

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.