package Integer;
public class Demo3 {
public static void main(String[] args) {
fun1();
}
private static void fun2() {
String x = "2";
String y = "23";
y = y.substring(0, 1);
System.out.println(y.equals(x)); // 输出为 true
System.out.println(x == y); // 输出为 false
}
private static void fun1() {
String str1 = "abc";
String str2 = "abc";
System.out.println(str2 == str1); // 输出为 true
System.out.println(str2.equals(str1)); // 输出为 true
String str3 = new String("abc");
String str4 = new String("abc");
System.out.println(str3 == str4); // 输出为 false
System.out.println(str3.equals(str4)); // 输出为 true
}
}<strong><u>
</u></strong>
fun1():
因为str1和str2没有实例化对象,所以赋值的数据“abc”都存放在方法区中,即指向一个内存地址,所以不论是通过“==”或是“equals()”进行比较,结果都是“true”;
但str3和str4都是重新实例化对象的,而“==”又是在比较两个对象的地址,所以通过“==”进行比较结果自然是“false”,而equals()则不同,因为equals()在源码中除了使用“==”号进行比较外还有另一种可能就是比较对象是否“instanceof String”, 然后将两个需要比较的字符串变为字符,比较长度和字符顺序(即比较两个字符串的内容是否相同)。下面附上equals()源码(其中注释是我自己加的……仅供参考……)。
public boolean equals(Object anObject) {
if (this == anObject) { //通过“==”进行比较,如果相等(即是一个对象)则直接返回true
return true;
}
if (anObject instanceof String) {
//如果参数anObject指向的是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;
}
--------------------------------------------------------------------------------------------------------------------------------------
fun2():
用equals()比较x和y的道理和fun1()一样;
而用“==”对a和b进行比较,虽然没有直接实例化对象,但是通过subString()则间接的实例化了对象,所以两个内存地址不相同则用“==”比较自然为“false”。下面附上subString()的源码。
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > value.length) {
throw new StringIndexOutOfBoundsException(endIndex);
}
int subLen = endIndex - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
return ((beginIndex == 0) && (endIndex == value.length)) ? this
: new String(value, beginIndex, subLen);
}
注:1、equals()是在比较两个对象的内存地址是否相同,其源码就是调用了“==”,所以通过equals()进行比较本质上和用“==”进行比较是没有区别的,但是,equals()是可以覆盖重写的,这个是比较方便的,而且equals()的源码比较是更为全面的,除了比较两个内存地址是否相同外,还特别针对指向Sting对象的特殊比较者进行内容的比较。
2、instanceof:出现在equals()的源码中,是用来判断一个引用是否指向指定的对象的一个关键字。(这个关键字全是小写,尤其注意“o”)
例:
class Demo{
public static void main(String[] args){
String str = new String();
if(str instanceof String){
System.out.println("true");
}else{
System.out.println("false");
}
}
}
================================================================================
这个两个例子是我在看“自动拆装箱”的问题时看到的……但是我不知道该如何从拆装箱分析……
只能通过equals()源码来解释……不知道对不对……希望得到大神的指点~~
希望能与更多的java程序员共同学习
扣扣联系:2531977855