其他
面试官:你工作三年了,还是不懂String!
以下文章来源于Java剑主 ,作者剑主
前语:不要为了读文章而读文章,一定要带着问题来读文章,勤思考。
来源:http://1t.click/aktS
# switch对String的支持
在switch中使用String:
public class Example {
public void test(String status) {
switch (status) {
case "wo":
break;
case "shi":
break;
case "jian":
break;
case "zhu":
break;
default:
break;
}
}
}
public class Example{
public void test(String status) {
byte var3 = -1;
switch(status.hashCode()) {
case 3800:
if (status.equals("wo")) {
var3 = 0;
}
break;
case 113844:
if (status.equals("shi")) {
var3 = 1;
}
break;
case 120583:
if (status.equals("zhu")) {
var3 = 3;
}
break;
case 3261868:
if (status.equals("jian")) {
var3 = 2;
}
}
}
# 为什么说String是“不可变的”呢?
public static void main(String[] args) {
String s = "123";
System.out.println("s = " + s);
s = "456";
System.out.println("s = " + s);
}
s = 123
s = 456
字符串操作方法:replaceFirst()、replaceAll()、replace(),也正是这种思想。
/** The value is used for character storage. */
private final char value[];
/** Cache the hash code for the string */
private int hash; // Default to 0
如下面这一段代码:
String s = "ABCabc";
System.out.println("s = " + s); //输出:ABCabc
String s1 = "ABCabc";
System.out.println("s1 = " + s1); //输出:ABCabc
String s2 = new String("ABCabc");
s1 != s2
# 字符串池、常量池、intern
本文重点在于String,所以常量池这块不做细究,有兴趣可以去看看相关材料。
# 字符串拼接的几种方式和区别/JDK1.8
1.使用“+”号
String a = "123";
String b = "456";
String c = a + b;
2.使用String的方法concat
String a = "123";
String b = "456";
String c = a.concat(b);
public String concat(String str) {
int otherLen = str.length();
if (otherLen == 0) {
return this;
}
int len = value.length;
char buf[] = Arrays.copyOf(value, len + otherLen);
str.getChars(buf, len);
return new String(buf, true);
}
3.使用StringBuilder的append
StringBuilder a = new StringBuilder("123");
String b = "456";
String c = a.append(b);
4.使用StringBuffer的append
StringBuffer a = new StringBuffer("123");
String b = "456";
String c = a.append(b);
# String,StringBuffer与StringBuilder的区别?
# 字符截取/JDK6与JDK7的不同。
String a = "0123456";
a = a.substring(1 , 4);
System.out.println(a); //123
String(int offset, int count, char value[]) {
this.value = value;
this.offset = offset;
this.count = count;
}
public String substring(int beginIndex, int endIndex) {
return new String(offset + beginIndex, endIndex - beginIndex, value);
}
上面也只是JDK6下的substring的实现原理。
public String(char value[], int offset, int count) {
this.value = Arrays.copyOfRange(value, offset, offset + count);
}
public String substring(int beginIndex, int endIndex) {
int subLen = endIndex - beginIndex;
return new String(value, beginIndex, subLen);
}
知识小鸡腿:String.valueOf() 解决了toString() 在参数为0的时候会报空指针异常的情况。