目录
字符串的构造
字符串的构造很简单,主要是三种分别是常量字符穿构造,直接new一个对象,用字符串数组进行构造
public class J_812 {
public static void main(String[] args) {
String s1 = "你好这里是CSDN";
System.out.println(s1);
String s2 = new String("ABC");
System.out.println(s2);
char[] arry = {'a','b','c'};
String s3 = new String(arry);
System.out.println(s3);
}
}
String类型在java里面是引用的它本身不能存储数据的,打开源码可以看到如下的内容
注意它是private修饰的所以它本身无法存储任何数据,下面举一个例子直观的认识一下引用的String 。
public static void main(String[] args) {
String s1 = new String("good");
String s2 = new String("boy");
String s3 =s2;
System.out.println(s3);
System.out.println(s1.length());
}
}
可以看到它是通过栈堆的引用的
字符串的比较
注意:对于内置类型,==比较的是变量中的值;对于引用类型==比较的是引用中的地址。
public static void main(String[] args) {
int a = 10;
int b = 20;
int c = 10;
// 对于基本类型变量,==比较两个变量中存储的值是否相同
System.out.println(a == b); // false
System.out.println(a == c); // true
// 对于引用类型变量,==比较两个引用变量引用的是否为同一个对象
String s1 = new String("hello");
String s2 = new String("hello");
String s3 = new String("world");
String s4 = s1;
System.out.println(s1 == s2); // false
System.out.println(s2 == s3); // false
System.out.println(s1 == s4); // true
}
因为前面说过String是引用类型,所以s1,s2,s3所对应的地址不一样,但是因为s4和s1都指向了同一个地址所以它们的值相同。所以我们要用到equals来比较
public static void main(String[] args) {
String s1 = new String("welcome");
String s2 = new String("welcome");
String s3 = new String("hi");
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
}
}
如果想比较字符串大小可以用int compareTo(String s)
public static void main(String[] args) {
String s1 = new String("we");
String s2 = new String("welce");
String s3 = new String("hi");
int ret = s1.compareTo(s2);
if (ret >0){
System.out.println("s1>s2");
}
else {
System.out.println("s1<s2");
}
}
}
//s1<s2
字符串常量池
public static void main(String[] args) {
String s1 = "hello";
String s2 = "hello";
String s3 = new String("hello");
String s4 = new String("hello");
System.out.println(s1 == s2); // true
System.out.println(s1 == s3); // false
System.out.println(s3 == s4); // false
}
这里的原因是s1,和s2都指向同一个地址,但是new出来的对象是唯一的,它们不在一个地址上
StringBuilder和StringBuffer
因为对String类进行修改时,效率是非常慢的,因此:尽量避免对String的直接需要,如果要修改建议尽量StringBuilder和StringBuffer。
public static void main(String[] args) {
long start = System.currentTimeMillis();
String s = "";
for(int i = 0; i < 100000; ++i){
s += i;
}
long end = System.currentTimeMillis();
System.out.println(end - start);
start = System.currentTimeMillis();
StringBuffer sbf = new StringBuffer("");
for(int i = 0; i < 100000; ++i){
sbf.append(i);
}
end = System.currentTimeMillis();
System.out.println(end - start);
start = System.currentTimeMillis();
StringBuilder sbd = new StringBuilder();
for(int i = 0; i < 100000; ++i){
sbd.append(i);
}
end = System.currentTimeMillis();