关于StringBuffer.setLength和trimToSize

首先声明jdk-version:7u40

好了,先新建一个StringBuffer.

StringBuffer aa = new StringBuffer("12345");

下面是jdk源码:

public StringBuffer(String str) {
        super(str.length() + 16);
        append(str);
}

super() :

AbstractStringBuilder(int capacity) {
        value = new char[capacity];
}

也就是说,StringBuffer新建了容量为字符串长度+16的字符数组.

StringBuffer aa = new StringBuffer("12345");
System.out.println(aa.capacity());//21
System.out.println(aa.length());//5

下面我们调用`setLength(int newLength)`

aa.setLength(16);

再次输出

System.out.println(aa.capacity());//21
System.out.println(aa.length());//16

其中16-5多出来的被`\0`补全了.

输出:

System.out.println(aa.toString());

public void setLength(int newLength) {
        if (newLength < 0)
            throw new StringIndexOutOfBoundsException(newLength);
        ensureCapacityInternal(newLength);

        if (count < newLength) {
            for (; count < newLength; count++)
                value[count] = '\0';
        } else {
            count = newLength;
        }
}

下面这句确认是否新设置的长度,大于现有char[]的长度,大于就要扩展容量.

 ensureCapacityInternal(newLength);
    public void ensureCapacity(int minimumCapacity) {
        if (minimumCapacity > 0)
            ensureCapacityInternal(minimumCapacity);
    }

    /**
     * This method has the same contract as ensureCapacity, but is
     * never synchronized.
     */
    private void ensureCapacityInternal(int minimumCapacity) {
        // overflow-conscious code
        if (minimumCapacity - value.length > 0)
            expandCapacity(minimumCapacity);
    }

    /**
     * This implements the expansion semantics of ensureCapacity with no
     * size check or synchronization.
     */
    void expandCapacity(int minimumCapacity) {
        int newCapacity = value.length * 2 + 2;
        if (newCapacity - minimumCapacity < 0)
            newCapacity = minimumCapacity;
        if (newCapacity < 0) {
            if (minimumCapacity < 0) // overflow
                throw new OutOfMemoryError();
            newCapacity = Integer.MAX_VALUE;
        }
        value = Arrays.copyOf(value, newCapacity);
    }

至于扩容...2倍+2

如果你设置的长度,小于现有的数据长度,也就是

aa.setLength(2);

那么输出:

System.out.println(aa.capacity());//21
System.out.println(aa.length());//2
System.out.println(aa.toString());//12

容量没变,记录char[]长度的成员变量值变了,至于value[]里的值并没有消失.证据是:

我调用了:

aa.append("aa");

然后打断点...

得到下面两张图:

由此可见,不仅没消失,append只是复写了它,也就是如果可以得到count的修改权,我们能找回以前的数据...不过,反正我没得到,你办到了记得通知我.

我们继续说trimToSize,解释是它会将value[](也就是char[])的长度(容量)改成数据的长度

调用:

		StringBuffer aa = new StringBuffer("12345");
		aa.setLength(2);
		aa.append("aa");
		aa.trimToSize();
		System.out.println(aa.capacity());//4
		System.out.println(aa.length());//4

源码:

/**
     * Attempts to reduce storage used for the character sequence.
     * If the buffer is larger than necessary to hold its current sequence of
     * characters, then it may be resized to become more space efficient.
     * Calling this method may, but is not required to, affect the value
     * returned by a subsequent call to the {@link #capacity()} method.
     */
    public void trimToSize() {
        if (count < value.length) {
            value = Arrays.copyOf(value, count);
        }
    }

copyOf:

/**
     * Copies the specified array, truncating or padding with null characters (if necessary)
     * so the copy has the specified length.  For all indices that are valid
     * in both the original array and the copy, the two arrays will contain
     * identical values.  For any indices that are valid in the copy but not
     * the original, the copy will contain <tt>'\\u000'</tt>.  Such indices
     * will exist if and only if the specified length is greater than that of
     * the original array.
     *
     * @param original the array to be copied
     * @param newLength the length of the copy to be returned
     * @return a copy of the original array, truncated or padded with null characters
     *     to obtain the specified length
     * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
     * @throws NullPointerException if <tt>original</tt> is null
     * @since 1.6
     */
    public static char[] copyOf(char[] original, int newLength) {
        char[] copy = new char[newLength];
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }

也就是说,它调用了copy数组的方法,使用现在记录的长度,复制了一个基于现数组和指定长度的数组,替代了旧数组,至于旧的,我觉得它是乖乖的去等GC了,不过没有证据,因为我追到这,就停了:

/**
     * Copies an array from the specified source array, beginning at the
     * specified position, to the specified position of the destination array.
     * A subsequence of array components are copied from the source
     * array referenced by <code>src</code> to the destination array
     * referenced by <code>dest</code>. The number of components copied is
     * equal to the <code>length</code> argument. The components at
     * positions <code>srcPos</code> through
     * <code>srcPos+length-1</code> in the source array are copied into
     * positions <code>destPos</code> through
     * <code>destPos+length-1</code>, respectively, of the destination
     * array.
     * <p>
     * If the <code>src</code> and <code>dest</code> arguments refer to the
     * same array object, then the copying is performed as if the
     * components at positions <code>srcPos</code> through
     * <code>srcPos+length-1</code> were first copied to a temporary
     * array with <code>length</code> components and then the contents of
     * the temporary array were copied into positions
     * <code>destPos</code> through <code>destPos+length-1</code> of the
     * destination array.
     * <p>
     * If <code>dest</code> is <code>null</code>, then a
     * <code>NullPointerException</code> is thrown.
     * <p>
     * If <code>src</code> is <code>null</code>, then a
     * <code>NullPointerException</code> is thrown and the destination
     * array is not modified.
     * <p>
     * Otherwise, if any of the following is true, an
     * <code>ArrayStoreException</code> is thrown and the destination is
     * not modified:
     * <ul>
     * <li>The <code>src</code> argument refers to an object that is not an
     *     array.
     * <li>The <code>dest</code> argument refers to an object that is not an
     *     array.
     * <li>The <code>src</code> argument and <code>dest</code> argument refer
     *     to arrays whose component types are different primitive types.
     * <li>The <code>src</code> argument refers to an array with a primitive
     *    component type and the <code>dest</code> argument refers to an array
     *     with a reference component type.
     * <li>The <code>src</code> argument refers to an array with a reference
     *    component type and the <code>dest</code> argument refers to an array
     *     with a primitive component type.
     * </ul>
     * <p>
     * Otherwise, if any of the following is true, an
     * <code>IndexOutOfBoundsException</code> is
     * thrown and the destination is not modified:
     * <ul>
     * <li>The <code>srcPos</code> argument is negative.
     * <li>The <code>destPos</code> argument is negative.
     * <li>The <code>length</code> argument is negative.
     * <li><code>srcPos+length</code> is greater than
     *     <code>src.length</code>, the length of the source array.
     * <li><code>destPos+length</code> is greater than
     *     <code>dest.length</code>, the length of the destination array.
     * </ul>
     * <p>
     * Otherwise, if any actual component of the source array from
     * position <code>srcPos</code> through
     * <code>srcPos+length-1</code> cannot be converted to the component
     * type of the destination array by assignment conversion, an
     * <code>ArrayStoreException</code> is thrown. In this case, let
     * <b><i>k</i></b> be the smallest nonnegative integer less than
     * length such that <code>src[srcPos+</code><i>k</i><code>]</code>
     * cannot be converted to the component type of the destination
     * array; when the exception is thrown, source array components from
     * positions <code>srcPos</code> through
     * <code>srcPos+</code><i>k</i><code>-1</code>
     * will already have been copied to destination array positions
     * <code>destPos</code> through
     * <code>destPos+</code><i>k</I><code>-1</code> and no other
     * positions of the destination array will have been modified.
     * (Because of the restrictions already itemized, this
     * paragraph effectively applies only to the situation where both
     * arrays have component types that are reference types.)
     *
     * @param      src      the source array.
     * @param      srcPos   starting position in the source array.
     * @param      dest     the destination array.
     * @param      destPos  starting position in the destination data.
     * @param      length   the number of array elements to be copied.
     * @exception  IndexOutOfBoundsException  if copying would cause
     *               access of data outside array bounds.
     * @exception  ArrayStoreException  if an element in the <code>src</code>
     *               array could not be stored into the <code>dest</code> array
     *               because of a type mismatch.
     * @exception  NullPointerException if either <code>src</code> or
     *               <code>dest</code> is <code>null</code>.
     */
    public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);

不过value的引用,指向已经替换成了copyOf回来的,那原数组也就是失去了引用,也就是不可达了吧,是吧?你也觉得它是等垃圾车了吧.

至于它是不是所谓的GC Roots对象,和GC Roots是否会被回收,我没有深究,如果你知道,请评论告诉我.

到此,就是我想记录的关于标题提到的两个方法,相关的事项.希望你能看完,虽然并没有什么卵用.

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-08-28 08:44:27

关于StringBuffer.setLength和trimToSize的相关文章

Java基础——数组应用之StringBuilder类和StringBuffer类

一.StringBuffer类 StringBuffer类和String一样,也用来代表字符串,只是由于StringBuffer的内部实现方式和String不同,所以StringBuffer在进行字符串处理时,不生成新的对象,在内存使用上要优于String类. 所以在实际使用时,如果经常需要对一个字符串进行修改,例如插入.删除等操作,使用StringBuffer要更加适合一些. 在StringBuffer类中存在很多和String类一样的方法,这些方法在功能上和String类中的功能是完全一样的

动态代理方案性能对比 (CGLIB,ASSIT,JDK)

动态代理工具比较成熟的产品有: JDK自带的,ASM,CGLIB(基于ASM包装),JAVAASSIST, 使用的版本分别为: JDK-1.6.0_18-b07, ASM-3.3, CGLIB-2.2, JAVAASSIST-3.11.0.GA (一) 测试结果: 数据为执行三次,每次调用一千万次代理方法的结果,测试代码后面有贴出. (1) PC机测试结果:Linux 2.6.9-42.ELsmp(32bit), 2 Cores CPU(Intel Pentium4 3.06GHz) Java代

Android解析XML之SAX解析器

SAX(Simple API for XML)解析器是一种基于事件的解析器,它的核心是事件处理模式,主要是围绕着事件源以及事件处理器来工作的.当事件源产生事件后,调用事件处理器相应的处理方法,一个事件就可以得到处理.在事件源调用事件处理器中特定方法的时候,还要传递给事件处理器相应事件的状态信息,这样事件处理器才能够根据提供的事件信息来决定自己的行为. SAX解析器的优点是解析速度快,占用内存少.非常适合在Android移动设备中使用. SAX相关类及API DefaultHandler:是一个事

数据存储(二)--SAX引擎XML存储(附Demo)

Android SDK只支持采用SAX技术读取XML,SAX采用顺序读取的方式来处理XML文档.这就要求在每读取XML文档的某个节点时会触发相应的事件来处理这个节点.下面基于一个实例讲述SAX的使用: public class Book { private String name; private String id; private String price; private String publisher; private int count; .... get,set方法省略 } XML

Java Day 15

String 字符串对象一旦被初始化就不会被改变  字符串常量池  String s = "abc"; //字符串常量池 String s = new String("abc");//在堆内存中 字符串== 比较地址值 String类中的equals复写了Object,比较字符串内容 String构造函数 常见方法 获取 转换 字符串切割  split  trim 判断 比较 intern方法 对字符串池进行操作 字符串数组排序获取字符串次数 1 private s

数据存储(两)--SAX发动机XML记忆(附Demo)

Android SDK支撑SAX读取技术XML,SAX通过连续的读取方式来处理XML文件.这要求每个读数XML对应的事件触发,以处理该节点的文件的节点.以下是基于一个例子来告诉SAX使用: public class Book { private String name; private String id; private String price; private String publisher; private int count; .... get,set方法省略 } XML文件例如以下

cglib源码分析1 ----- 缓存和KEY

cglib是一个java 字节码的生成工具,它是对asm的进一步封装,提供了一系列class generator.研究cglib主要是因为它也提供了动态代理功能,这点和jdk的动态代理类似. 一. Cache的创建 与jdk动态代理一样,cglib也提供了缓存来提高系统的性能,对于已经生成的类,直接使用而不必重复生成.这里不得不提到一个比较重要的抽象类AbstractClassGenerator,它采用了模版方法的设计模式,protected Object create(Object key)

spark Accumulator累加器使用示例

官网 http://spark.apache.org/docs/2.3.1/rdd-programming-guide.html#accumulators http://spark.apache.org/docs/2.3.1/api/scala/index.html#org.apache.spark.util.AccumulatorV2 Accumulator是spark提供的累加器,累加器的一个常用用途是在调试时对作业执行过程中的事件进行计数,但是只要driver能获取Accumulator的

JavaSE8基础 StringBuffer delete trimToSize 清空字符串缓冲区与整理缓冲区的空间

os :windows7 x64    jdk:jdk-8u131-windows-x64    ide:Eclipse Oxygen Release (4.7.0)        code: package jizuiku1; public class Demo100 { public static void main(String[] args) { StringBuffer sb = new StringBuffer(); sb.append("cnblog"); System.