String(二)(JAVA学习笔记)

字符串一旦定义不可改变:

字符串的底层实现实际上就是数组,如下为String的jdk源码:

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence
{
    /** The value is used for character storage. */
    private final char value[];

    /** The offset is the first index of the storage that is used. */
    private final int offset;

    /** The count is the number of characters in the String. */
    private final int count;
public String() {
	this.offset = 0;
	this.count = 0;
	this.value = new char[0];
    }

缺陷为长度固定,字符串的内容是无法改变的,分析如下代码:

String str = "hello";
str = str + "world";
str += "!!!";
System.out.println(str);

运行截图:


分析内存图:


在此过程中,只是字符串引用对象发生改变,字符串内容没有发生改变。在以上代码的过程中不断的产生了垃圾。

总结:

  1. 字符串直接赋值
  2. 字符串使用equals()方法比较
  3. 字符串尽量别改变,否则会产生很多垃圾
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值