第六周動手動腦問題
請運行以下示例代碼StringPool.java,查看其輸出結果。如何解釋這樣的輸出結果?從中你能總結出什麽?
在Java中,內容相同的字串常量(“Hello”)只保存一份以節約內存,所以s0,s1,s2實際上引用的是同一個對象。編譯器在編譯s2一句時,會去掉“+”號,直接把兩個字串連接起來得一個字串(“Hello”)。這種優化工作由Java編譯器自動完成。當直接使用new關鍵字創建字符串對象時,雖然值一致(都是“Hello”),但仍然是兩個獨立的對象。
為什麽會有上述的輸出結果?從中你又能總結出什麽?
給字串變量賦值意味著:兩個變量(s1,s2)現在引用同一個字符串對象“a”!String
使用equals()或equalsIgnoreCase()方法比較兩字串內容是否相同,使用==比較兩字串變量是否引用同一字串對象。compareTo:使用字典法進行比較,返回0表兩字串相等,小於返回負值,大於返回正值。egionMatches:比較兩字串中的某一部分是否相等
結果:
字符串查找方法:
查詢字串是否以某字串開頭和結尾:startsWith和endWith方法
在字串查找字符或子串,調用indexOf和lastIndexOf方法即可。
請閱讀JDK中String類上述方法的源碼,模仿其編程方式,編寫一個MyCounter類,它的方法也支持上述的“級聯”調用特性,其調用示例為:
MyCounter counter1=new MyCounter(1);
MyCounter counter2=counter1.increase(100).decrease(2).increase(3);
public class MyCounter {
private
public int getC() {
return c;
}
public void setC(int c) {
this.c = c;
}
MyCounter(int c)
{
this.c = c;
}
public static void main(String[] args) {
MyCounter counter1=new MyCounter(1);
MyCounter counter2=counter1.increase(100).decrease(2).increase(3);
System.out.println(counter2.c);
}
public MyCounter increase(int c)
{
this.c=this.c+c;
return this;
}
public MyCounter decrease(int c)
{
this.c=this.c-c;
return this;
}
}
結果:
java中length()用來獲取String字符串的長度
public class TestS {
public static void main(String[] args) {
// TODO 自動生成的方法存根
int a;
char[] b,d;
char c;
String e,f,g,h;
String s="abcde";
a=s.length();//獲取字符串長度
b=s.toCharArray();//換成字符數組
c=s.charAt(1);//獲取特定位置的字符
d=s.toCharArray();//換成字符數組
s.getChars(0, 0, d, 0);
e=s.replace("a", "e");//將a替換成e
f=s.toUpperCase();//換成大寫
g=s.toLowerCase();//換成小寫
h=s.trim();//賦值
System.out.println(a+"\n"+c+"\n"+e+"\n"+f+"\n"+g+"\n"+h);
}
}
第六周動手動腦問題