扩展:String的底层原理
package com.qf.test09;
public class Test01 {
public static void main(String[] args) {
String str1 = new String("abc");
String str2 = new String("abc");
System.out.println(str1 == str2);
System.out.println(str1.equals(str2));
System.out.println(str1);
System.out.println(str2);
System.out.println("--------------------------------");
MyString m1 = new MyString("abc");
MyString m2 = new MyString("abc");
System.out.println(m1 == m2);
System.out.println(m1.equals(m2));
System.out.println(m1);
System.out.println(m2);
}
}
package com.qf.test09;
public class MyString {
private char[] value;
public MyString(String original) {
value = original.toCharArray();
}
@Override
public boolean equals(Object obj) {
if(this == obj){
return true;
}
MyString m = (MyString) obj;
char[] v1 = this.value;
char[] v2 = m.value;
int len = v1.length;
if(len != v2.length){
return false;
}
for (int i = 0; i < len; i++) {
if(v1[i] != v2[i]){
return false;
}
}
return true;
}
@Override
public String toString() {
String str = "";
for (char c : value) {
str += c;
}
return str;
}
}