社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
在理解String类之前,需要了解java内存的栈(对象引用)、堆(对象本身)和方法区(共享数据区,常量池等)等。此处不做赘述。
public boolean equals(Object obj) {
return (this == obj);
}
Student student1 = new Student();
Student student2 = new Student();
System.out.println(student1 + "n" + student2);// com.raptor.entity.Student@106d69c
// com.raptor.entity.Student@52e922
System.out.println(student1 == student2);// false
System.out.println(student1.equals(student2));// false
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
String newS1 = new String("hello");
String newS2 = new String("hello");
String ss1 = "hello";
String ss2 = "hello";
System.out.println("ss1==ss2是" + (ss1 == ss2));//true
System.out.println("ss1==newS1是" + (ss1 == newS1));//false
System.out.println("newS1==newS2是" + (newS1 == newS2));//false
String类的引用可以指向不同的字符串,这是因为字符串对象虽然是不能修改的, 但是它们的地址可以共享。
java中String类型不可变,‘+’的实现:jvm复制了一份“hello”对象与“world”做拼接,并没有改变原来的“hello”的值。
String s = "hello";
s+="world";
System.out.println(s); //helloworld
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!