问题大概是这样的,问下面这个程序在运行时生成了几个Custom类和String对象,并说明为什么public class Custom
{
String name;
public Custom(String aname)
{
this.name = aname;
} public String getName()
{
return name;
}
}public class Someclass
{
...
public static void main(String args[])
{
Custom one = new Custom("Hello ");
Custom two = one;
Custom three = new Custom(one.getName + "World");
System.out.prinln(one.getName);
System.out.prinln(two.getName);
System.out.prinln(three.getName);
}
}
{
String name;
public Custom(String aname)
{
this.name = aname;
} public String getName()
{
return name;
}
}public class Someclass
{
...
public static void main(String args[])
{
Custom one = new Custom("Hello ");
Custom two = one;
Custom three = new Custom(one.getName + "World");
System.out.prinln(one.getName);
System.out.prinln(two.getName);
System.out.prinln(three.getName);
}
}
一个Custom ,一个String
Custom two = one;
一个Custom ,
Custom three = new Custom(one.getName + "World");
一个Custom ,一个String一共3个Custom ,2个String!!
System.out.println(one == three);
System.out.println(one.getName() == two.getName());
System.out.println(one.getName() == three.getName());运行结果应该是:
true
false
true
false
说明:
one, two引用同一个对象,这个不要解释了吧。关于字符串,csdn上已经有很多介绍了,对于直接给定字符串,比如"Hello",这是存放在对象池中的,所有的String s = "Hello", 都是引用对象池中的同一个对象,而s = new String("Hello");就是在堆空间中分配新的内存,新建一个对象了。
//一个Custom 对象,,并且一个"Hello" 对象
Custom one = new Custom("Hello ");
//没有创建对象,只是另一个引用指向了one指向的对象地址
Custom two = one;
//又生成一个Custom 对象,这里不是创建2个String对象吗?一个"World",一个"hello World")
Custom three = new Custom(one.getName + "World");
System.out.prinln(one.getName);
System.out.prinln(two.getName);
System.out.prinln(three.getName);
觉得是三个String对象,同意楼上的
String类型name 作为对象的一个属性自然也在堆中.所以会有 3 个 String
three 单独指向新对象
2个custom
3个string!
Custom three = new Custom(one.getName + "World"); 这是一个string对象呢!
Custom two = one; //引用指向的是和上面one的同一个对象。
Custom three = new Custom(one.getName + "World"); //在String池里两个String对象,堆里一个对象。堆里共2个对象,String池共三个对象
{
...
public static void main(String args[])
{
Custom one = new Custom("Hello "); //这里创建第一个Custom对象,和第一个String对象"Hello "
Custom two = one;// two只是引用第一个Custom对象
Custom three = new Custom(one.getName + "World"); //这里创建第二个Custom对象,和第二个String对象"Hello World"
System.out.prinln(one.getName);
System.out.prinln(two.getName);
System.out.prinln(three.getName);
}
}
new Custom(one.getName + "World")
的时候,"World"要生成一个String,相加后要另外创建一个String来存放"Hello World"