回顾JavaSE(4)-String(3)四行代码分析String字面值对象和构造方法对象的内存分配

本文通过四个代码示例,解析了 Java 中通过 String 字面值和构造方法创建对象的区别,并结合内存分配图进行深入讲解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天我们通过四行代码分析String字面值对象和构造方法创建对象的不同,附上内存分配图,深入理解。

首先,必须明确:

==:若是引用类型,比较的是地址值是否相同。
equals:若是引用类型,默认比较的是地址值是否相同,但Sting类重写了equals方法,比较内容是否相同。

     /**
     * Compares this string to the specified object.  The result is {@code
     * true} if and only if the argument is not {@code null} and is a {@code
     * String} object that represents the same sequence of characters as this
     * object.
     *
     * @param  anObject
     *         The object to compare this {@code String} against
     *
     * @return  {@code true} if the given object represents a {@code String}
     *          equivalent to this string, {@code false} otherwise
     *
     * @see  #compareTo(String)
     * @see  #equalsIgnoreCase(String)
     */
    public boolean equals(Object anObject) {
	if (this == anObject) {
	    return true;
	}
	if (anObject instanceof String) {
	    String anotherString = (String)anObject;
	    int n = count;
	    if (n == anotherString.count) {
		char v1[] = value;
		char v2[] = anotherString.value;
		int i = offset;
		int j = anotherString.offset;
		while (n-- != 0) {
		    if (v1[i++] != v2[j++])
			return false;
		}
		return true;
	    }
	}
	return false;
    }

然后,我们写一下代码:

<span style="white-space:pre">	</span>String s9 = new String("Hello");
	String s10 = "Hello";
	System.out.println("s9 == s10:" + (s9 == s10));
	System.out.println("s9.equals(s10):" + s9.equals(s10));
大家可以猜一猜输出结果是啥?

第一个false,第二个true,你猜对了吗?

为什么会这样?

请看内存分配图(栈、堆、方法区-字符串常量池):



看了图,瞬间秒懂有木有。

这也是一道经典的面试题:

String构造方法创造对象可能创建2或1个对象;

String字面值创造对象可能创建1/0个对象。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值