JDK源码学习系列02----AbstractStringBuilder

因为看StringBuffer 和 StringBuilder 的源码时发现两者都继承了AbstractStringBuilder,并且很多方法都是直接super的父类AbstractStringBuilder的方法,所以还是决定先看AbstractStringBuilder的源码,然后再看StringBuffer 和 StringBuilder.

1.成员变量

AbstractStringBuilder和String一样,在其内部都是以字符数组的形式实现的。也就是String,StringBuffer以及StringBuilder在其内部都是以字符数组的形式实现的。

 char value[];
int count;

2.构造函数

AbstractStringBuilder的构造函数中传入的capacity是指容量,实际长度是以leng中的count表示的,注意区分容量和实际长度。

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

3.容量和长度

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

4.AbstractStringBuilder的扩容

public void ensureCapacity(int minimumCapacity) {
if (minimumCapacity > value.length) {//如果传入的容量大于原来的容量就扩容
expandCapacity(minimumCapacity);
}
} void expandCapacity(int minimumCapacity) {
int newCapacity = (value.length + 1) * 2;//首先默认扩容为 (原容量+1)*2
if (newCapacity < 0) {
newCapacity = Integer.MAX_VALUE;
} else if (minimumCapacity > newCapacity) {//如果传入的容量大于 默认扩容量,则传入容量为新容量
newCapacity = minimumCapacity;
}
value = Arrays.copyOf(value, newCapacity);
}

5.字符串减少存储空间

如果实际长度小于容量,为了减少存储空间,就把容量缩小为刚好满足字符串长度。

public void trimToSize() {
if (count < value.length) {
value = Arrays.copyOf(value, count);
}
}

6.void setLength(int newLength)

public void setLength(int newLength) {
if (newLength < 0)
throw new StringIndexOutOfBoundsException(newLength);
if (newLength > value.length)//设置长度大于容量时先扩容
expandCapacity(newLength); if (count < newLength) {//设置长度大于原来长度时,后面部分补以空白
for (; count < newLength; count++)
value[count] = '\0';
} else {
count = newLength;
}
}

7.char charAt(int index)

public char charAt(int index) {
if ((index < 0) || (index >= count))
throw new StringIndexOutOfBoundsException(index);
return value[index];
}

8.void getChars(int srcBegin, int srcEnd, char dst[],  int dstBegin)

一定要注意参数情况的考虑,自己编程时一定要养成好习惯。主要是调用了System.arraycopy()的方法,以后具体分析。

 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);
}

9.void setCharAt(int index, char ch)

方法的源码很简单,是直接替换该index的值,而不是后移之类的,因为是数组,不可变长度。

 public void setCharAt(int index, char ch) {
if ((index < 0) || (index >= count))
throw new StringIndexOutOfBoundsException(index);
value[index] = ch;
}

10.append(String str)

对于StringBuffer和StringBuilder重要的append()方法的源码闪亮登场咯~~

public AbstractStringBuilder append(String str) {
if (str == null) str = "null";//若传入为null,则会在后面加上“null”
int len = str.length();
if (len == 0) return this;//传入长度为0,则返回本身
int newCount = count + len;
if (newCount > value.length)//传入后的长度大于容量就扩容
expandCapacity(newCount);
str.getChars(0, len, value, count);//用的是getChars()为value传值
count = newCount;
return this;
}

11.append(CharSequence s, int start, int end)

 public AbstractStringBuilder append(CharSequence s, int start, int end) {
if (s == null)
s = "null";
if ((start < 0) || (end < 0) || (start > end) || (end > s.length()))//一定要注意情况考虑
throw new IndexOutOfBoundsException(
"start " + start + ", end " + end + ", s.length() "
+ s.length());
int len = end - start;
if (len == 0)
return this;
int newCount = count + len;
if (newCount > value.length)
expandCapacity(newCount);
for (int i=start; i<end; i++)//用的是charAt()为value循环赋值
value[count++] = s.charAt(i);//!!
count = newCount;
return this;
}

12.append(char str[])

若是字符数组,用的是System.arraycopy()方法。

 public AbstractStringBuilder append(char str[]) {
int newCount = count + str.length;
if (newCount > value.length)
expandCapacity(newCount);
System.arraycopy(str, 0, value, count, str.length);
count = newCount;
return this;
}

13.append(boolean b)

这个源码很简单

 public AbstractStringBuilder append(boolean b) {
if (b) {
int newCount = count + 4;
if (newCount > value.length)
expandCapacity(newCount);
value[count++] = 't';
value[count++] = 'r';
value[count++] = 'u';
value[count++] = 'e';
} else {
int newCount = count + 5;
if (newCount > value.length)
expandCapacity(newCount);
value[count++] = 'f';
value[count++] = 'a';
value[count++] = 'l';
value[count++] = 's';
value[count++] = 'e';
}
return this;
}

14.append(int i)

public AbstractStringBuilder append(int i) {
if (i == Integer.MIN_VALUE) {
append("-2147483648");
return this;
}
int appendedLength = (i < 0) ? stringSizeOfInt(-i) + 1 : stringSizeOfInt(i);//!!!
int spaceNeeded = count + appendedLength;
if (spaceNeeded > value.length)
expandCapacity(spaceNeeded);
Integer.getChars(i, spaceNeeded, value);
count = spaceNeeded;
return this;
}
    final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
99999999, 999999999, Integer.MAX_VALUE }; // Requires positive x
static int stringSizeOfInt(int x) {
for (int i=0; ; i++)
if (x <= sizeTable[i])
return i+1;
}

15.delete(int start, int end)

主要还是用的System.arraycopy()

public AbstractStringBuilder delete(int start, int end) {
if (start < 0)
throw new StringIndexOutOfBoundsException(start);
if (end > count)
end = count;
if (start > end)
throw new StringIndexOutOfBoundsException();
int len = end - start;
if (len > 0) {
System.arraycopy(value, start+len, value, start, count-end);
count -= len;
}
return this;
}

16.reverse()

这个是StringBuffer和StringBuilder常用到的方法,而String并没有这个牛逼的功能~~

public AbstractStringBuilder reverse() {
boolean hasSurrogate = false;
int n = count - 1;
for (int j = (n-1) >> 1; j >= 0; --j) {
char temp = value[j];
char temp2 = value[n - j];
if (!hasSurrogate) {
hasSurrogate = (temp >= Character.MIN_SURROGATE && temp <= Character.MAX_SURROGATE)
|| (temp2 >= Character.MIN_SURROGATE && temp2 <= Character.MAX_SURROGATE);
}
value[j] = temp2;
value[n - j] = temp;
}
if (hasSurrogate) {
// Reverse back all valid surrogate pairs
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;
}
}
}
}
return this;
}

17. String toString()

这个只是一个抽象的方法,没有方法体。

 public abstract String toString();

JDK源码学习系列02----AbstractStringBuilder的更多相关文章

  1. JDK源码学习系列03----StringBuffer+StringBuilder

                         JDK源码学习系列03----StringBuffer+StringBuilder 由于前面学习了StringBuffer和StringBuilder的父类A ...

  2. JDK源码学习系列05----LinkedList

                                             JDK源码学习系列05----LinkedList 1.LinkedList简介 LinkedList是基于双向链表实 ...

  3. JDK源码学习系列04----ArrayList

                                                                             JDK源码学习系列04----ArrayList 1. ...

  4. JDK源码学习系列01----String

                                                     JDK源码学习系列01----String 写在最前面: 这是我JDK源码学习系列的第一篇博文,我知道 ...

  5. JDK源码学习笔记——Integer

    一.类定义 public final class Integer extends Number implements Comparable<Integer> 二.属性 private fi ...

  6. Spring5.0源码学习系列之浅谈BeanFactory创建

    Spring5.0源码学习系列之浅谈BeanFactory创建过程 系列文章目录 提示:Spring源码学习专栏链接 @ 目录 系列文章目录 博客前言介绍 一.获取BeanFactory主流程 二.r ...

  7. Java并发包源码学习系列:CLH同步队列及同步资源获取与释放

    目录 本篇学习目标 CLH队列的结构 资源获取 入队Node addWaiter(Node mode) 不断尝试Node enq(final Node node) boolean acquireQue ...

  8. Java并发包源码学习系列:挂起与唤醒线程LockSupport工具类

    目录 LockSupport概述 park与unpark相关方法 中断演示 blocker的作用 测试无blocker 测试带blocker JDK提供的demo 总结 参考阅读 系列传送门: Jav ...

  9. Java并发包源码学习系列:阻塞队列实现之PriorityBlockingQueue源码解析

    目录 PriorityBlockingQueue概述 类图结构及重要字段 什么是二叉堆 堆的基本操作 向上调整void up(int u) 向下调整void down(int u) 构造器 扩容方法t ...

随机推荐

  1. QT插件开发方式(没看懂)

    创建一个QT的库项目,删除自动生成的.h和.cpp文件,添加一个接口定义.h文件和一个接口实现类(一个.h一个.cpp).代码如下: 1.接口文件源码 #ifndef PLUGININTERFACE_ ...

  2. HDU 1142 A Walk Through the Forest(dijkstra+记忆化DFS)

    题意: 给你一个图,找最短路.但是有个非一般的的条件:如果a,b之间有路,且你选择要走这条路,那么必须保证a到终点的所有路都小于b到终点的一条路.问满足这样的路径条数 有多少,噶呜~~题意是搜了解题报 ...

  3. Linux 双网卡绑定技术

    bond技术是在linux2.4以后加入内核. 一般步骤是1.把bonding模块加入内核, 2 编辑要绑定的网卡设置,去除地址设定 3 添加bond设备,设置地址等配置 4  重启网络 5 在交换机 ...

  4. Windows查看进程taskList,终止进程tskill

    TaskList:         列出当前所有运行进程.         使用方法:在命令提示符中输入tasklist 然后回车,会看到类似下面的列表: 映像名称                   ...

  5. Python Object Graphs — objgraph 1.7.2 documentation

    Python Object Graphs - objgraph 1.7.2 documentation Python Object Graphs¶ objgraph is a module that ...

  6. 使用URLConnection提交请求

    URL的openConnection()方法将返回一个URLConnection对象,该对象表示应用程序和URL之间的通信连接.程序可以通过URLConnection实例向该URL发送请求,读取URL ...

  7. [Android学习笔记]LinearLayout布局,剩余空间的使用

    转自:http://segmentfault.com/q/1010000000095725 如果使得一个View占用其父View的剩余空间? 答案是使用:android:layout_weight = ...

  8. Note:This element neither has attached source nor attached Javadoc

    在用Eclipse编写程序时,发现把鼠标放到类名上时出现标题的提示 解决方法: 右击项目,选择 properties –> Java Build Path –> Libraries,如图 ...

  9. Linux实现字符设备驱动的基础步骤

    Linux应用层想要操作kernel层的API,比方想操作相关GPIO或寄存器,能够通过写一个字符设备驱动来实现. 1.先在rootfs中的 /dev/ 下生成一个字符设备.注意主设备号 和 从设备号 ...

  10. MTK Android Driver:GPIO

    watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvY2JrODYxMTEw/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA ...