new String比字符串池浪費(fèi)空間,為什么要用它?
對(duì)于下面程序中:ss0 = new String( "hello" );是用new()來(lái)新建對(duì)象的,存于堆中。每調(diào)用一次就會(huì)創(chuàng)建一個(gè)新的對(duì)象。當(dāng)然從節(jié)省空間的角度來(lái)講,肯定不如str="hello",有童鞋一定問(wèn),那要它有什么用?當(dāng)時(shí)設(shè)計(jì)編譯器時(shí),為什么要設(shè)計(jì)它?馬克-to-win,那我請(qǐng)問(wèn)你,如果在你編程序時(shí),你還不知道字符串內(nèi)容怎么辦?這時(shí)就用到new String(String original),所以,什么都有什么的用處。
(注意不能看調(diào)試窗口里value id,eclipse的問(wèn)題)
馬克- to-win:馬克 java社區(qū):防盜版實(shí)名手機(jī)尾號(hào): 73203。
本章源碼
public class Test
{
public static void main(String args[]) {
String str, str1, ss0, ss1, ss2, ss3, ss4;
str = "hello";
str1 = "hello";
ss0 = new String("hello");
ss1 = new String("hello");
ss2 = new String("bye");
ss3 = new String("chi le ma");
ss4 = new String("chi le ma");
/* ==在測(cè)內(nèi)存地址是否相同,如果相同,就證明是同一個(gè)對(duì)象。== means address space is the same.str and str1 point to the same
String constant.only one place
*/
System.out.println(str1 == str);
System.out.println(ss1 == ss0);
/* equals 是看內(nèi)容是否相等,equals means as long as value is the same, it is the same.but == mean
memory address should be the same. */
System.out.println(ss1.equals("hello"));
System.out.println(str1 == "hello");
System.out.println(ss1 == "hello");
}
}
result is:
true
false
true
true
false
String class contains a static method, valueOf(). With it, you can create a String object from a value of any of the basic types
String pi = String.valueOf(3.14159);
String對(duì)象的運(yùn)算符:“+”。用來(lái)連接兩個(gè)字符串。
一件需要注意的事:
你不能寫(xiě)如下一段程序,系統(tǒng)會(huì)崩潰的,馬克-to-win,因?yàn)樗蚻ang包當(dāng)中的類名String沖突,所以不要用lang包當(dāng)中的類名當(dāng)類名。因?yàn)閘ang包是核心包。you can not write a program like the following, the system will collapse. because it will collide with the class with the package of java.lang, so remember that don't try to use the name of class of java.lang package.
你可以用其他包當(dāng)中的類名當(dāng)類名寫(xiě)程序。比如io包當(dāng)中File類。you can rewrite a class named File because it is java.io package.
class String{
String(int a)
{
System.out.println("a is"+a);
}
}
public class Test {
public static void main(String[] args) {
String d=new String(8);
}
}
輸出結(jié)果:
java.lang.NoSuchMethodError: main
Exception in thread "main"