String类
常用方法:
String string = " qweretJSDFIJDFOjojgilkkdf ";
System.out.println(string.toCharArray());
System.out.println(string.trim());
System.out.println(string.toLowerCase());
System.out.println(string.toUpperCase());
System.out.println(string.charAt(25));
System.out.println(string.replace("ere", "sss"));
// replaceAll支持正则表达式
System.out.println(string.replaceAll("ere", "sss"));
System.out.println(string.endsWith(" "));
System.out.println(string.startsWith(" "));
System.out.println(string.substring(10, 20));
byte[] bytes = string.getBytes();
for (byte byte0 : bytes) {
System.out.print(byte0 + " ");
}
System.out.println(string.indexOf("e"));
System.out.println(string.lastIndexOf("e"));
String[] split = string.split("j");
for (String ss : split) {
System.out.println(ss);
}
String s = " ";
System.out.println(s.isBlank());
System.out.println(s.isEmpty());
System.out.println(string.intern());
String ss = "a";
//直接存放在常量池中
String s1 = new String("s");
//先在堆中创建对象,然后在常量池中创建常量
String s1 = "a";
String s2 = "b";
String s4 = "a"+"b";
String s3 = "ab";
System.out.println(s4==s3);
//输出结果true,因为s1,s2已经在常量池中创建了常量,所以s3,s4直接指向常量池中的值,不会创建新的
StringBuilder与StringBuffer
String在使用是不会是在原String上经行操作,而是创建新String经行操作(String实现原理是字符串数组)
StringBuilder线程不安全,但是运行速度快
StringBuffer线程安全,但是运行速度比StringBuilder慢
StringBuffer和StringBuilder提供字符串反转操作方法(实现原理是动态数组,开始是长度为16,当数组长度不够时,经行动态扩容16<<1 + 2,第一次扩容到达34位)
//StringBuilder扩容方式(JDK17)
public AbstractStringBuilder append(int i) {
int count = this.count;
int spaceNeeded = count + Integer.stringSize(i);
ensureCapacityInternal(spaceNeeded);
if (isLatin1()) {
Integer.getChars(i, spaceNeeded, value);
} else {
StringUTF16.getChars(i, count, spaceNeeded, value);
}
this.count = spaceNeeded;
return this;
}
public AbstractStringBuilder append(int i) {
int count = this.count;
int spaceNeeded = count + Integer.stringSize(i);
ensureCapacityInternal(spaceNeeded);
if (isLatin1()) {
Integer.getChars(i, spaceNeeded, value);
} else {
StringUTF16.getChars(i, count, spaceNeeded, value);
}
this.count = spaceNeeded;
return this;
}
private int newCapacity(int minCapacity) {
int oldLength = value.length;
int newLength = minCapacity << coder;
int growth = newLength - oldLength;
int length = ArraysSupport.newLength(oldLength, growth, oldLength + (2 << coder));
if (length == Integer.MAX_VALUE) {
throw new OutOfMemoryError("Required length exceeds implementation limit");
}
return length >> coder;
}
包装类
8中基本类型都有包装类
int-->Interger char-->Charact float-->Float(其他的都为首字母大写)
创建方式
Interger i = new Interger();
自动装箱
Interger i = Interger.valueOf(int 值);
自动拆箱
int i = Interger类型的值;
Integer aa =基本类型.intValue();
注:包装类中都存有一些值,Interger中的是【-128,127】,其它类中也有,具体值包装类都不同
// 等于 是 i1 = Integer.valueOf(23)
Integer i12 = 23;
Integer i22 = 23;
// true
System.out.println(i12 == i22);
//直接找Interger中已经存在的【-128,127】,不会创建
Integer i3 = new Integer(44);
Integer i4 = new Integer(44);
//new 的方式会直接创建堆中对象
// false
System.out.println(i3 == i4);
// true
System.out.println(i3.equals(i4));