String&StringBuilder
String
的底层数据结构是数组char value[]
1 2 3 4 5 6 7 8 9 public final class String implements java .io.Serializable, Comparable<String>, CharSequence { private final char value[]; private int hash; private static final long serialVersionUID = -6849794470754667710L ; }
String的类用于存放字符串的方法都用了final来修饰,也就是创建后均不可以被改变,当我们进行一个字符串相连的操作时,便会创建出新的对象
1 2 3 4 5 6 7 8 9 10 String str_1 = new String ("ab" );String str_2 = new String ("ab" );String str_3 = "ab" ; System.out.println(str_1 == str_2); System.out.println(str_1 == str_2.intern()); System.out.println(str_1.intern() == str_2.intern()); System.out.println(str_1 == str_3); System.out.println(str_1.intern() == str_3);
结论:
== , 在引用类型中是对比的地址,比如str1和str2,两个new出来的对象置于堆内存中,地址肯定不同;但是如果是基础类型如str3,就是对比值;当然也有equal方法,这是对比的是哈希值
intern(),这是一个本地方法,底层由c++实现,它的作用是将值推进常量池
String str_3 = "ab"
这种赋值方法JVM做了优化,不会创建对象,直接将值放进常量池
StringBuilder
1 2 3 4 5 6 7 8 9 new StringBuilder (16 );public StringBuilder () { super (16 ); } AbstractStringBuilder(int capacity) { value = new char [capacity]; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 stringBuilder.append("a" );public AbstractStringBuilder append (String str) { if (str == null ) return appendNull(); int len = str.length(); ensureCapacityInternal(count + len); str.getChars(0 , len, value, count); count += len; return this ; }private void ensureCapacityInternal (int minimumCapacity) { if (minimumCapacity - value.length > 0 ) expandCapacity(minimumCapacity); }void expandCapacity (int minimumCapacity) { int newCapacity = value.length * 2 + 2 ; if (newCapacity - minimumCapacity < 0 ) newCapacity = minimumCapacity; if (newCapacity < 0 ) { if (minimumCapacity < 0 ) throw new OutOfMemoryError (); newCapacity = Integer.MAX_VALUE; } value = Arrays.copyOf(value, newCapacity); }
对字符串的各种操作方法 字符串类
String:不可修改
当使用字符串的相加操作时,不会删掉原字符串,而是在常量池里面新建一个新的String,储存修改后的结果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 equals(); compareTo(); contains(); indexOf(); startsWith(); endsWith(); replaceAll(String regex,String replacement); split(String regex); String[] arr = str.split("," ); substring(); trim(); toUpperCase();toLowerCase(); join("mark" ,"" );
StringBuilder:可以修改,可以在常量池里原地修改字符串
StringBuffer:可以修改,且线程安全,基本与StringBuilder相同
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 append(); toString(); setCharAt(int i, char c); insert(int offset, String str/char c); delete(int startIndex,int endIndex); deleteCharAt (int index); replace(int start,int end,String str); reverse(); substring(int start,int end);
如何将ArrayList转换为数组?
1 2 3 4 5 6 7 8 9 10 ArrayList<Integer> list = new ArrayList <>();for (int i = 0 ; i < 10 ; i++) { list.add(i); } Object[] o = list.toArray();for (Object value : o) { int num = (int ) value; System.out.println(num); }