下面两条机器有什么区别?

realjoshzuo 2003-03-12 02:08:31
String s = "asdf";


String s = new String("asdf");
...全文
20 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
bjzhanghao 2003-03-12
  • 打赏
  • 举报
回复
这次明白了,楼主给分吧
wojue 2003-03-12
  • 打赏
  • 举报
回复
不好意思,剛才說錯了
應該是
String s = new String("asdf");
是直接產生一個新的實例
String s = "asdf";
是先到堆中尋找是否有"asdf"這個對象,如果有,則讓s指向他,如果沒有,則產生一個新的實例


public class test
{
public static void main(String args[]){
String t1="ab";
String t2="ab"; //new String("abc");
String t3=new String("abc");
String t4="abc";
System.out.println(t1);
System.out.println(t2);
System.out.println(t3);
if (t1==t2)
System.out.println("==");
else
System.out.println("!=");
}
}
這裡可以看出t1和t2的地址是相同的
niuji 2003-03-12
  • 打赏
  • 举报
回复
String s = "asdf";
其实建了string,s和"asdf"
niuji 2003-03-12
  • 打赏
  • 举报
回复
wojue() 的反了

kkhui 2003-03-12
  • 打赏
  • 举报
回复
纯粹胡扯

这是这个构造函数的实现:

public String(String original) {
this.count = original.count;
if (original.value.length > this.count) {
// The array representing the String is bigger than the new
// String itself. Perhaps this constructor is being called
// in order to trim the baggage, so make a copy of the array.
this.value = new char[this.count];
System.arraycopy(original.value, original.offset,
this.value, 0, this.count);
} else {
// The array representing the String is the same
// size as the String, so no point in making a copy.
this.value = original.value;
}
}
bjzhanghao 2003-03-12
  • 打赏
  • 举报
回复
我一直认为二者是完全相同的,楼上的牛,谢谢了!
wojue 2003-03-12
  • 打赏
  • 举报
回复
String s = "asdf";
是直接產生一個新的實例
String s = new String("asdf");
是先到堆中尋找是否有"asdf"這個對象,如果有,則讓s指向他,如果沒有,則產生一個新的實例

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧