java字符串對(duì)象String
實(shí)現(xiàn)可序列化(java.io.Serializable),可比較(Comparable<String>)就乓,字符序列(CharSequence)。
基本屬性
//char[] 作為底層存儲(chǔ)
private final char value[]
//有私有的創(chuàng)建時(shí)生成的hash屬性噩翠,
private int hash;
//包含一個(gè)私有對(duì)象流字段數(shù)組ObjectStreamField[] serialPersistentFields守伸,稍后在做研究
private static final ObjectStreamField[] serialPersistentFields =
new ObjectStreamField[0];
一些基本的構(gòu)造函數(shù)
這里不一一貼出了,大致包含了见芹,無參(空字符串)蠢涝,char[],char[]高階徘铝,byte[],byte[]高階怕午,int[]高階以及 byte[]&Charset,byte[] & String(charset string)淹魄,StringBuffer,StringBuilder等
//比較常用的聲明方式包括
//從常量池構(gòu)建
String s = "abc";
//堆構(gòu)建
String s = new String("abc");
char[] sc = {'a','b','c'};
String s = new String(sc);
String bs = new String("你好".getBytes(),"utf-8");
基本方法
一些比較好理解的(可以通過方法名稱字面意思理解的)
charAt,codePointAt,codePointBefore,codePointCount,compareTo,compareToIgnoreCase(不區(qū)分大小寫),concat(拼接到尾部),contains,contentEquals,contentEquals(CharSequence cs),contentEquals(StringBuffer sb)兆蕉,static copyValueOf(從char[]或者char[]指定區(qū)域構(gòu)建)缤沦,endsWith,equals(值比較)缸废,equalsIgnoreCase(不區(qū)分大小寫值比較),static format(通過某種表達(dá)式和參數(shù)構(gòu)建)养晋,getBytes(普通和高階用法)梁钾,getChars,hashCode(返回私有屬性hash值)零酪,indexOf拇勃,intern(返回字符串對(duì)象的規(guī)范表示),isEmpty月腋,static join(由 CharSequence elements的副本組成,并附有指定的delimiter的 delimiter )榆骚,lastIndexOf煌集,length,matches碉钠,offsetByCodePoints(返回此 String內(nèi)的指數(shù),與 index codePointOffset代碼點(diǎn))喊废,regionMatches,replace褂策,replaceAll,replaceFirst,split(切分)耿焊,startsWith,subSequence器腋,substring钩杰,toCharArray,toLowerCase(轉(zhuǎn)換為消協(xié))措左,toUpperCase(轉(zhuǎn)換為大寫)避除,trim和一系列的valueOf方法。
知識(shí)
聲明/創(chuàng)建方式
//String特殊創(chuàng)建方式以及構(gòu)造函數(shù)創(chuàng)建方式的區(qū)別
/**
在使用特殊創(chuàng)建方式(String s = "";)方式創(chuàng)建字符串對(duì)象時(shí)凉逛,
虛擬機(jī)會(huì)先去檢查常量池(什么是常量池可以在jvm相關(guān)知識(shí)中找到)中是否存在相同值的對(duì)象,
如果不存在就在常量池中創(chuàng)建一個(gè)状飞,如果存在直接返回該對(duì)象书斜,
而使用構(gòu)造函數(shù)創(chuàng)建時(shí),是在堆內(nèi)存中創(chuàng)建String對(duì)象自晰,
這樣就導(dǎo)致了不同形式創(chuàng)建的同樣的值的String對(duì)象的地址比較的差異性
*/
String str="helloworld";
String str1="helloworld";
String str2=new String("helloworld");
String str3=new String("helloworld");
System.out.println(":"+(str==str1));
System.out.println(":"+(str1==str2));
System.out.println(":"+(str2==str3));
System.out.println(":"+str.equals(str3));
輸出結(jié)果如下:
true
false
false
true
使用char[]構(gòu)造
當(dāng)使用char[]構(gòu)造String對(duì)象時(shí)稍坯,方法的實(shí)現(xiàn)是直接使用Arrays,copyOf方法直接給屬性value賦值
使用byte[]構(gòu)建
借助StringCoding類給屬性value賦值
startsWith & endsWith
startsWith遍歷char[]一一比較
endsWith同時(shí)使用startsWith完成的