下面的程序怎么重写tostring方法使输出结果为这两个引用的地址值,而不是真实值?package fortest;public class Test{
public static void main(String[] args){
String s="abc";
String s1="abc";
System.out.println(s);
System.out.println(s1);
}
public String toString(){
return "";
}
}tostring
public static void main(String[] args){
String s="abc";
String s1="abc";
System.out.println(s);
System.out.println(s1);
}
public String toString(){
return "";
}
}tostring
package fortest;public class Test{
public static void main(String[] args){
Test t=new Test();
System.out.println(t);
}
}
输出结果为fortest.Test@18a992f
这样吧,你告诉你想获得的结果是什么样的?
是s的地址?
s1的地址?
s的值?
s1的值?
谁调用toString方法。。
这样会理解的更明白一些。
As much as is reasonably practical, the hashCode method defined by
* class <tt>Object</tt> does return distinct integers for distinct
* objects. (This is typically implemented by converting the internal
* address of the object into an integer, but this implementation
* technique is not required by the
也就是说hashCode其实反映的是Object的内存地址,是用C是实现的
String s = new String("344");则会创建2个对象,一个是栈中,一个是堆中,堆中对象是对栈中的引用。String s = "ree";
String s2 = "ree"; 其实用的是一个栈中的对象,不会创建2个,和普通的Object对象不同,JVM对String对象做了优化
Sring s = "123"不是在String池中创建么?怎么到栈中创建了
String类已经重写了Object的toString方法和hashCode方法,想找到在地址值的线索已经让屏蔽掉了。你这个请求是没办法完了。
String这个类可以简单的去理解,第一个String对象有字符串信息,以后有新String类对象,只要和第一个String对象有相同的字符序列,就直接去引用第一个String的字符串,自己不会保存字符串信息了。可以用String类的intern()方法去获得第一个String对象的引用。