package com.baidu.test;
import org.junit.Test;
/**
* String相关
*
*/
public class Test_String {
/**
* 1.switch支持String么? 原理? 支持
*
* 通过反编译字节码文件得知,switch是通过字符串的hashCoe值来判断是否相等的,若val的hashCode值和case对应的字符串的hashCode值一样,则进入该case
* 并且为了防止哈希冲突,在case内又使用equals来比较两个字符串的值.
*
*/
@Test
public void string_switch() throws Exception {
String val = "aa";
switch(val){
case "bb":
System.out.println("bb");
break;
case "aa":
System.out.println("aa");
break;
default:
System.out.println("default...");
}
}
/*
* 反编译字节
*
public void string_switch_class() throws Exception {
String val = "aa";
String s;
switch ((s = val).hashCode()) {
default:
break;
case 3104:
if (!s.equals("aa"))
break;
System.out.println("aa");
break;
case 3136:
if (s.equals("bb")) {
System.out.println("bb");
break;
}
break;
}
System.out.println("default...");
}
*/
/**
* 2.拼接字符串使用StringBuilder一定比String快么?
*
* 情况一:String str = "he"+"llo"+"world";//6毫秒 循环10000000次
* StringBuilder sb = new StringBuilder("he").append("llo").append("world");//620毫秒 循环10000000次
*
* 情况二:String a = "a";
* String b = "b";
* String c = "c";
* String ret = a+b+c; //920毫秒 循环10000000次
* StringBuilder builder = new StringBuilder().append(a).append(b).append(c); //540毫秒 循环10000000次
*
* 从情况二来看,StringBuilder要比String快。
* 但是情况一来看,String要比StringBuilder快非常多
* 为什么情况一中String这么快, 其实虚拟机把String str = "he"+"llo"+"world"看成了String str="helloworld"; 根本就没有进行拼接,所以如此之快。
* 但是其他情况下真正拼接字符串是还是StringBuilder要快。
*
*/
@Test //测试情况一
public void testStrigJoint1() throws Exception {
long begin = System.currentTimeMillis();
StringBuilder sb = new StringBuilder();
for(int i=0;i<10000000;i++){
//String str = "he"+"llo"+"world";
sb = new StringBuilder("he").append("llo").append("world");
}
long end = System.currentTimeMillis();
System.out.println(end-begin);
}
@Test //测试情况二
public void testStringJoint2() throws Exception {
long begin = System.currentTimeMillis();
StringBuilder sb = new StringBuilder();
String a ="a";
String b ="b";
String c ="c";
for(int i=0;i<10000000;i++){
//String ret =a+b+c;
sb.append(a).append(b).append(c);
}
long end = System.currentTimeMillis();
System.out.println(end-begin);
}
//String
/**
* 3.比较两个字符串使用equals方法,不要使用==来比较
*/
@Test
public void testString() throws Exception {
String a = "hello";
String b = "helloo";
String c = "hello";
String substring = b.substring(0,5);
System.out.println(substring==a);//false
System.out.println(a==c);//true
/*
* 实际上只有字符串常量是共享的, 而+,substring()产生的字符串是不共享的.
* 所以a和substring两个字符串的地址是不一样的.如果使用==来比较则为false
*
*/
}
}