public final class String implements java.io.Serializable, Comparable<String>, CharSequence {private final char[] value; private int hash; ///hash值 public String(String original) { this.value = original.value;//['a','b','c过去的值赋值 this.hash = original.hash;//['a','b','chash值赋值过去 } public int hashCode() { int h = hash; if (h == 0 && value.length > 0) { char val[] = value; //['a','b','c'] for (int i = 0; i < value.length; i++) { h = 31 * h + val[i];///hash算法 } hash = h;//96354 } return h; } }
package com.qf.switch_string;import java.io.PrintStream;public class Test01{ public static void main(String args[]){ label0:{String str = "Aa";String s;///临时字符串 ///本质获得的strhash值switch ((s = str).hashCode(){/2112 default:break;case 2112: ///AA和BB的hash值if (!s.equals("Aa")){if (s.equals("BB")){System.out.println("BB");break label0;}} else{System.out.println("Aa");break label0;}break;case 119193: if (!s.equals("xyz"))break;System.out.println("xyz");break label0;}System.out.println(“默认”);}}}
public static void main(String[] args) {//注意:两个不同的字符串hash值可能相同.out.println("Aa".hashCode());//2112System.out.println("BB".hashCode());//2112String str = "Aa";switch (str) {case "abc":System.out.println("abc");break;case "def":System.out.println("def");break;case "xyz":System.out.println("xyz");break;default:System.out.println(“默认”);break;}}
总结:底层处理逻辑:先判断hash值,再比较字符串的内容(equals)因为两个字符串的hash值可能相同,所以需要比较内容