深入学习java源码之StringBuilder.indexOf()与StringBuilder.reverse()

本文深入探讨了Java中的StringBuilder类,详细分析了indexOf()和reverse()方法的工作原理,同时介绍了toString()方法的实现,以及System.out.println的源码细节。通过本文,读者将对StringBuilder的内部机制有更深入的理解。

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

深入学习java源码之StringBuilder.indexOf()与StringBuilder.reverse()

java的toString()方法

在Java中每个类都默认继承Object类,除非声明继承某个类。而Object类中有一个叫做toString的方法。该方法返回的是该Java对象的内存地址经过哈希算法得出的int类型的值在转换成十六进制。这个输出的结果可以等同的看作Java对象在堆中的内存地址。

我们知道,在输出一个类的时候,如果没有重写父类的toString方法的话,打印的将会是Book@987876,即

public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

所以只有子类重写父类的toString()方法之后,才会打印你想输出的信息。

System.out.println的源码:

public void println(Object x) {
        String s = String.valueOf(x);
        synchronized (this) {
            print(s);
            newLine();
        }
    }

String.valueOf(),

public static String valueOf(Object obj) {
        return (obj == null) ? "null" : obj.toString();
}

 

 

Modifier and TypeMethod and Description
intcapacity()

返回当前容量。

charcharAt(int index)

返回 char在指定索引在这个序列值。

voidensureCapacity(int minimumCapacity)

确保容量至少等于规定的最小值。

voidgetChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

字符从该序列复制到目标字符数组 dst

intindexOf(String str)

返回指定子字符串第一次出现的字符串内的索引。

intindexOf(String str, int fromIndex)

返回指定子串的第一次出现的字符串中的索引,从指定的索引开始。

intlastIndexOf(String str)

返回指定子字符串最右边出现的字符串内的索引。

intlastIndexOf(String str, int fromIndex)

返回指定子字符串最后一次出现的字符串中的索引。

intlength()

返回长度(字符数)。

intoffsetByCodePoints(int index, int codePointOffset)

返回此序列中与 indexcodePointOffset代码点偏移的索引。

StringBuilderreverse()

导致该字符序列被序列的相反代替。

voidsetCharAt(int index, char ch)

指定索引处的字符设置为 ch

voidsetLength(int newLength)

设置字符序列的长度。

CharSequencesubSequence(int start, int end)

返回一个新的字符序列,该序列是该序列的子序列。

Stringsubstring(int start)

返回一个新的 String ,其中包含此字符序列中当前包含的字符的子序列。

Stringsubstring(int start, int end)

返回一个新的 String ,其中包含此序列中当前包含的字符的子序列。

StringtoString()

返回表示此顺序中的数据的字符串。

voidtrimToSize()

尝试减少用于字符序列的存储。

java源码

package java.lang;

public final class StringBuilder
    extends AbstractStringBuilder
    implements java.io.Serializable, CharSequence
{

    static final long serialVersionUID = 4383685877147921099L;

    public StringBuilder() {
        super(16);
    }

    public StringBuilder(int capacity) {
        super(capacity);
    }

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

    public StringBuilder(CharSequence seq) {
        this(seq.length() + 16);
        append(seq);
    }
	
    @Override
    public int indexOf(String str) {
        return super.indexOf(str);
    }

    @Override
    public int indexOf(String str, int fromIndex) {
        return super.indexOf(str, fromIndex);
    }

    @Override
    public int lastIndexOf(String str) {
        return super.lastIndexOf(str);
    }

    @Override
    public int lastIndexOf(String str, int fromIndex) {
        return super.lastIndexOf(str, fromIndex);
    }

    @Override
    public StringBuilder reverse() {
        super.reverse();
        return this;
    }

    @Override
    public String toString() {
        // Create a copy, don't share the array
        return new String(value, 0, count);
    }
	
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException {
        s.defaultWriteObject();
        s.writeInt(count);
        s.writeObject(value);
    }
	
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        s.defaultReadObject();
        count = s.readInt();
        value = (char[]) s.readObject();
    }	
}
package java.lang;

import sun.misc.FloatingDecimal;
import java.util.Arrays;

abstract class AbstractStringBuilder implements Appendable, CharSequence {

    char[] value;
	
    int count;	
	
    AbstractStringBuilder() {
    }

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

    @Override
    public int length() {
        return count;
    }

    public int capacity() {
        return value.length;
    }

    private int newCapacity(int minCapacity) {
        // overflow-conscious code
        int newCapacity = (value.length << 1) + 2;
        if (newCapacity - minCapacity < 0) {
            newCapacity = minCapacity;
        }
        return (newCapacity <= 0 || MAX_ARRAY_SIZE - newCapacity < 0)
            ? hugeCapacity(minCapacity)
            : newCapacity;
    }	
	
    private void ensureCapacityInternal(int minimumCapacity) {
        // overflow-conscious code
        if (minimumCapacity - value.length > 0) {
            value = Arrays.copyOf(value,
                    newCapacity(minimumCapacity));
        }
    }	

    public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
    {
        if (srcBegin < 0)
            throw new StringIndexOutOfBoundsException(srcBegin);
        if ((srcEnd < 0) || (srcEnd > count))
            throw new StringIndexOutOfBoundsException(srcEnd);
        if (srcBegin > srcEnd)
            throw new StringIndexOutOfBoundsException("srcBegin > srcEnd");
        System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);
    }
	
    public int indexOf(String str) {
        return indexOf(str, 0);
    }
	
    public int indexOf(String str, int fromIndex) {
        return String.indexOf(value, 0, count, str, fromIndex);
    }
	
    public int lastIndexOf(String str) {
        return lastIndexOf(str, count);
    }

    public int lastIndexOf(String str, int fromIndex) {
        return String.lastIndexOf(value, 0, count, str, fromIndex);
    }

    public AbstractStringBuilder reverse() {
        boolean hasSurrogates = false;
        int n = count - 1;
        for (int j = (n-1) >> 1; j >= 0; j--) {
            int k = n - j;
            char cj = value[j];
            char ck = value[k];
            value[j] = ck;
            value[k] = cj;
            if (Character.isSurrogate(cj) ||
                Character.isSurrogate(ck)) {
                hasSurrogates = true;
            }
        }
        if (hasSurrogates) {
            reverseAllValidSurrogatePairs();
        }
        return this;
    }	
	
    private void reverseAllValidSurrogatePairs() {
        for (int i = 0; i < count - 1; i++) {
            char c2 = value[i];
            if (Character.isLowSurrogate(c2)) {
                char c1 = value[i + 1];
                if (Character.isHighSurrogate(c1)) {
                    value[i++] = c1;
                    value[i] = c2;
                }
            }
        }
    }
	
    public String substring(int start) {
        return substring(start, count);
    }
	
    @Override
    public CharSequence subSequence(int start, int end) {
        return substring(start, end);
    }

    public String substring(int start, int end) {
        if (start < 0)
            throw new StringIndexOutOfBoundsException(start);
        if (end > count)
            throw new StringIndexOutOfBoundsException(end);
        if (start > end)
            throw new StringIndexOutOfBoundsException(end - start);
        return new String(value, start, end - start);
    }	
	
    @Override
    public abstract String toString();
	
    final char[] getValue() {
        return value;
    }
	
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wespten

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值