1. 程式人生 > >第六周動手動腦問題

第六周動手動腦問題

優化 image 手動 ret 調用示例 mat 代碼 動手 字符數組

請運行以下示例代碼StringPool.java,查看其輸出結果。如何解釋這樣的輸出結果?從中你能總結出什麽?

技術分享

Java中,內容相同的字串常量(“Hello”)只保存一份以節約內存,所以s0s1s2實際上引用的是同一個對象。編譯器在編譯s2一句時,會去掉“+”號,直接把兩個字串連接起來得一個字串(“Hello”)。這種優化工作由Java編譯器自動完成。當直接使用new關鍵字創建字符串對象時,雖然值一致(都是“Hello”),但仍然是兩個獨立的對象。

技術分享

為什麽會有上述的輸出結果?從中你又能總結出什麽?

給字串變量賦值意味著:兩個變量(s1s2)現在引用同一個字符串對象“a”!String

對象的內容是只讀的,使用“+”修改s1變量的值,實際上是得到了一個新的字符串對象,其內容為“ab”,它與原先s1所引用的對象”a”無關,所以,s1==s2返回false;代碼中的“ab”字符串是一個常量,它所引用的字符串與s1所引用的“ab”對象無關。String.equals()方法可以比較兩個字符串的內容。

使用equals()equalsIgnoreCase()方法比較兩字串內容是否相同,使用==比較兩字串變量是否引用同一字串對象。compareTo:使用字典法進行比較,返回0表兩字串相等,小於返回負值,大於返回正值。egionMatches:比較兩字串中的某一部分是否相等

技術分享

結果:

技術分享

字符串查找方法:

查詢字串是否以某字串開頭和結尾:startsWithendWith方法

在字串查找字符或子串,調用indexOflastIndexOf方法即可。

請閱讀JDK中String類上述方法的源碼,模仿其編程方式,編寫一個MyCounter類,它的方法也支持上述的“級聯”調用特性,其調用示例為:

MyCounter counter1=new MyCounter(1);

MyCounter counter2=counter1.increase(100).decrease(2).increase(3);

public class MyCounter {

private

int c;

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);
}
}

第六周動手動腦問題