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','c']的hash值赋值过去
}
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;//临时的字符串
//本质获取的str的hash值
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值有可能相同
System.out.println("Aa".hashCode());//2112
System.out.println("BB".hashCode());//2112
String 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值有可能相同,所以需要比较内容
标签:hash,String,System,break,switch,源码,println,out From: https://blog.51cto.com/u_16154651/6465467