String类型的成员变量

/** String的属性值 */
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. */
/**String中元素的个数**/
private final int count; /** Cache the hash code for the string */
/**String类型的hash值**/
private int hash; // Default to 0 /** use serialVersionUID from JDK 1.0.2 for interoperability */
private static final long serialVersionUID = -6849794470754667710L;

  有上面的成员变量可以知道String类的值是final类型的,不能被改变的,所以只要一个值改变就会生成一个新的String类型对象,存储String数据也不一定从数组的第0个元素开始的,而是从offset所指的元素开始。

如下面的代码是生成了一个新的对象,最后的到的是一个新的值为“bbaa”的新的String的值。

     String a = new String("bb");
String b = new String("aa");
String c = a + b;

  也可以说String类型的对象是长度不可变的,String拼接字符串每次都要生成一个新的对象,所以拼接字符串的效率肯定没有可变长度的StringBuffer和StringBuilder快。

然而下面这种情况却是很快的拼接两个字符串的:

    String a = "aa" + "bb";

  原因是:java对它字符串拼接进行了小小的优化,他是直接把“aa”和“bb”直接拼接成了“aabb”,然后把值赋给了a,只需生成一次String对象,比上面那种方式减少了2次生成String,效率明显要高很多。


下面我们来看看String的几个常见的构造方法

1、无参数的构造方法:

public String() {
this.offset = 0;
this.count = 0;
this.value = new char[0];
}

2、传入一个Sring类型对象的构造方法

public String(String original) {
int size = original.count;
char[] originalValue = original.value;
char[] v;
if (originalValue.length > size) {
// The array representing the String is bigger than the new
// String itself. Perhaps this constructor is being called
// in order to trim the baggage, so make a copy of the array.
int off = original.offset;
v = Arrays.copyOfRange(originalValue, off, off+size);
} else {
// The array representing the String is the same
// size as the String, so no point in making a copy.
v = originalValue;
}
this.offset = 0;
this.count = size;
this.value = v;
}

3、传入一个字符数组的构造函数

public String(char value[]) {
int size = value.length;
this.offset = 0;
this.count = size;
this.value = Arrays.copyOf(value, size);
}

4、传入一个字符串数字,和开始元素,元素个数的构造函数

public String(char value[], int offset, int count) {
if (offset < 0) {
throw new StringIndexOutOfBoundsException(offset);
}
if (count < 0) {
throw new StringIndexOutOfBoundsException(count);
}
// Note: offset or count might be near -1>>>1.
if (offset > value.length - count) {
throw new StringIndexOutOfBoundsException(offset + count);
}
this.offset = 0;
this.count = count;
this.value = Arrays.copyOfRange(value, offset, offset+count);
}

  由上面的几个常见的构造函数可以看出,我们在生成一个String对象的时候必须对该对象的offset、count、value三个属性进行赋值,这样我们才能获得一个完成的String类型。


常见函数:

1、判断两个字符串是否相等的函数(Equal):其实就是首先判断比较的实例是否是String类型数据,不是则返回False,是则比较他们每一个字符元素是否相同,如果都相同则返回True,否则返回False

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

2、比较两个字符串大小的函数(compareTo):输入是两个字符串,返回的0代表两个字符串值相同,返回小于0则是第一个字符串的值小于第二个字符串的值,大于0则表示第一个字符串的值大于第二个字符串的值。

  比较的过程主要如下:从两个字符串的第一个元素开始比较,实际比较的是两个char的ACII码,加入有不同的值,就返回第一个不同值的差值,否则返回0

public int compareTo(String anotherString) {
int len1 = count;
int len2 = anotherString.count;
int n = Math.min(len1, len2);
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset; if (i == j) {
int k = i;
int lim = n + i;
while (k < lim) {
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2) {
return c1 - c2;
}
k++;
}
} else {
while (n-- != 0) {
char c1 = v1[i++];
char c2 = v2[j++];
if (c1 != c2) {
return c1 - c2;
}
}
}
return len1 - len2;
}

3、判断一个字符串是否以prefix字符串开头,toffset是相同的长度

public boolean startsWith(String prefix, int toffset) {
char ta[] = value;
int to = offset + toffset;
char pa[] = prefix.value;
int po = prefix.offset;
int pc = prefix.count;
// Note: toffset might be near -1>>>1.
if ((toffset < 0) || (toffset > count - pc)) {
return false;
}
while (--pc >= 0) {
if (ta[to++] != pa[po++]) {
return false;
}
}
return true;
} public int hashCode() {
int h = hash;
if (h == 0) {
int off = offset;
char val[] = value;
int len = count; for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
}
return h;
}

4、连接两个字符串(concat)

public String concat(String str) {
int otherLen = str.length();
if (otherLen == 0) {
return this;
}
char buf[] = new char[count + otherLen];
getChars(0, count, buf, 0);
str.getChars(0, otherLen, buf, count);
return new String(0, count + otherLen, buf);
}

连接字符串的几种方式

1、最直接,直接用+连接

     String a = new String("bb");
String b = new String("aa");
String c = a + b;

2、使用concat(String)方法

      String a = new String("bb");
String b = new String("aa");
String d = a.concat(b);

3、使用StringBuilder

 String a = new String("bb");
String b = new String("aa"); StringBuffer buffer = new StringBuffer().append(a).append(b);

  第一二中用得比较多,但效率比较差,使用StringBuilder拼接的效率较高。

java String部分源码解析的更多相关文章

  1. Java集合---LinkedList源码解析

    一.源码解析1. LinkedList类定义2.LinkedList数据结构原理3.私有属性4.构造方法5.元素添加add()及原理6.删除数据remove()7.数据获取get()8.数据复制clo ...

  2. Java 8 ThreadLocal 源码解析

    Java 中的 ThreadLocal是线程内的局部变量, 它为每个线程保存变量的一个副本.ThreadLocal 对象可以在多个线程中共享, 但每个线程只能读写其中自己的副本. 目录: 代码示例 源 ...

  3. Java泛型底层源码解析-ArrayList,LinkedList,HashSet和HashMap

    声明:以下源代码使用的都是基于JDK1.8_112版本 1. ArrayList源码解析 <1. 集合中存放的依然是对象的引用而不是对象本身,且无法放置原生数据类型,我们需要使用原生数据类型的包 ...

  4. 【Java实战】源码解析Java SPI(Service Provider Interface )机制原理

    一.背景知识 在阅读开源框架源码时,发现许多框架都支持SPI(Service Provider Interface ),前面有篇文章JDBC对Driver的加载时应用了SPI,参考[Hibernate ...

  5. Java集合-ArrayList源码解析-JDK1.8

    ◆ ArrayList简介 ◆ ArrayList 是一个数组队列,相当于 动态数组.与Java中的数组相比,它的容量能动态增长.它继承于AbstractList,实现了List, RandomAcc ...

  6. Java线程池源码解析

    线程池 假如没有线程池,当存在较多的并发任务的时候,每执行一次任务,系统就要创建一个线程,任务完成后进行销毁,一旦并发任务过多,频繁的创建和销毁线程将会大大降低系统的效率.线程池能够对线程进行统一的分 ...

  7. Java之ConcurrentHashMap源码解析

    ConcurrentHashMap源码解析 目录 ConcurrentHashMap源码解析 jdk8之前的实现原理 jdk8的实现原理 变量解释 初始化 初始化table put操作 hash算法 ...

  8. JAVA常用集合源码解析系列-ArrayList源码解析(基于JDK8)

    文章系作者原创,如有转载请注明出处,如有雷同,那就雷同吧~(who care!) 一.写在前面 这是源码分析计划的第一篇,博主准备把一些常用的集合源码过一遍,比如:ArrayList.HashMap及 ...

  9. Java泛型底层源码解析--ConcurrentHashMap(JDK1.7)

    1. Concurrent相关历史 JDK5中添加了新的concurrent包,相对同步容器而言,并发容器通过一些机制改进了并发性能.因为同步容器将所有对容器状态的访问都串行化了,这样保证了线程的安全 ...

随机推荐

  1. 推荐使用C++ 11

    如果你的代码工作正常并且表现良好,你可能会想知道为什么还要使用C++ 11.当然了,使用用最新的技术感觉很好,但是事实上它是否值得呢? 在我看来,答案毫无疑问是肯定的.我在下面给出了9个理由,它们分为 ...

  2. Netty学习之服务器端创建

    一.服务器端开发时序图 图片来源:Netty权威指南(第2版) 二.Netty服务器端开发步骤 使用Netty进行服务器端开发主要有以下几个步骤: 1.创建ServerBootstrap实例 Serv ...

  3. 与众不同 windows phone 8.0 & 8.1 系列文章索引

    [源码下载] [与众不同 windows phone 7.5 (sdk 7.1) 系列文章索引] 与众不同 windows phone 8.0 & 8.1 系列文章索引 作者:webabcd ...

  4. u-boot移植总结(一)start.S分析

    本次移植u-boot-2010.09是基于S3C2440的FL440板子,板子自带NANDFLASH而没有NORFLASH,所以在U-BOOT启动的过程中必须实现从NANDFLASH到SDRAM的重定 ...

  5. Orchard中文版源码下载

    本版本基于Orchard1.7.2修改: 新增Bootstrap主题 新增中文语言包 增加了对Sqlite.Orchard数据库的支持 优化工程,减少临时符号生成,增加工程效率 和一些BUG的修正 默 ...

  6. 深入浅出java 8 lambda表达式--零基础一分钟入门

    lambda从使用上来说,第一感觉直白的理解就是,少了很多不必要的匿名回调类的写法,比如: public static void main(String[] args) { PlatformQuery ...

  7. java.lang.RuntimeException: Fail to connect to camera service问题

    做音视频录制功能的真机调试的时候出现这个问题 错误意思为无法连接到相机服务 可能由两种情况导致 1.配置清单文件没有设置相应的权限 <uses-permission android:name=& ...

  8. Python基础(10)--数字

    本文的主题是 Python 中的数字.会详细介绍每一种数字类型,它们适用的各种运算符, 以及用于处理数字的内建函数.在文章的末尾, 简单介绍了几个标准库中用于处理数字的模块. 本文地址:http:// ...

  9. Android性能优化--Listview优化

    ListView的工作原理 首先来了解一下ListView的工作原理(可参见http://mobile.51cto.com/abased-410889.htm),如图: ListView 针对每个it ...

  10. UIButton在不同状态下显示不同背景色

    参考自:原文地址(内容与原文并无区别,只是自己以后方便使用整理了一下) 1.UIButton的background是不支持在针对不同的状态显示不同的颜色. 2.UIButton的backgroundI ...