String和StringBuffer
String: string特性:不可变性(因为final修饰)、多线程安全、字符串常量池 在Java中,由于会大量的使用String常量,如果每一次声明一个String都创建一个String对象,那将会造 成极大的空间资源的浪费。Java提出了String pool的概念,在堆中开辟一块存储空间String pool,当初 始化一个String变量时,如果该字符串已经存在了,就不会去创建一个新的字符串变量,而是会返回已 经存在了的字符串的引用。 但使用String b = new String("aaa");,程序会在堆内存中开辟一片新空间存放新对象,同时会将”aaa”字符串放入常量池,相当于创建了两个对象,无论常量池中有没有”aaa”字符串,程序都会在堆内存中开辟一片新空间存放新对象 。
- 类似还有int和Integer区别详解 (opens new window)** **
public class test {
public static void main(String[] args) {
String a = "adc";
String b = "adc";
String s1 = new String("adc");
String s2 = new String("adc");
System.out.println(a==b);//true
System.out.println(s1==s2);//false
System.out.println(a==s1);//false
System.out.println(a.equals(s1));//true
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Java String 类 | 菜鸟教程 (opens new window)
StringBuffer 和 StringBuilder 类主要用于对字符串进行修改: Java StringBuffer 和 StringBuilder 类 | 菜鸟教程 (opens new window) 或者字符串.toCharArray()后对字符数组修改操作
# 构造:
Stringstr = "Runoob"; Stringstr2=new String("Runoob");
char[ ] helloArray = {'r', 'u', 'n', 'o', 'o', 'b'}; String helloString = new String(helloArray);
- StringBuffer (opens new window)()构造一个字符串缓冲区,其中没有字符,初始容量为16个字符。
- StringBuffer (opens new window)(int capacity)构造一个字符串缓冲区,其中没有字符和指定的初始容量。
- StringBuffer (opens new window)(CharSequence (opens new window) seq)构造一个字符串缓冲区,其中包含与指定的 CharSequence相同的字符。
- StringBuffer (opens new window)(String (opens new window) str)构造一个初始化为指定字符串内容的字符串缓冲区。
和StringBuilder (opens new window)的构造器一样
# 方法
- StringBuffer、StringBuilder 类主要方法:
StringBuffer append(String s) StringBuffer reverse() 整体反转 delete(int start, int end) StringBuffer/Builder deleteCharAt(int index) insert(int offset, String str) void setCharAt(int index, char ch)
- String独有的:
int indexOf(int ch) (opens new window)或(int ch, int fromIndex) char[] toCharArray() (opens new window) String[] split(String regex, int limit) (opens new window) contains(CharSequence chars) (opens new window)或String str
- 两种类都有的:
int length() char charAt(int index) (opens new window) ->等价于toCharArray( )后利用 ch[index]或增强for遍历 int indexOf(String str) (opens new window)或(String str, int fromIndex) String toString() String substring(int beginIndex) (opens new window) String substring(int beginIndex, int endIndex) (opens new window)
- beginIndex -- 起始索引(包括), 索引从 0 开始。
- endIndex -- 结束索引(不包括)