[英]why does it print “tostring” twice?
这是我的课,请解释为什么它两次打印“ tostring”
public class HashCodeAndEquals
{
static String asd;
public HashCodeAndEquals(String string) {
asd = string;
}
/**
* @param args
*/
public static void main(String[] args) {
HashCodeAndEquals obj1 = new HashCodeAndEquals("one");
HashCodeAndEquals obj2 = new HashCodeAndEquals("two");
System.out.println(obj1.toString());
//System.out.println(obj2.toString());
System.out.println(obj1.equals(obj2));
System.out.println(obj1==obj2);
}
@Override
public String toString() {
// TODO Auto-generated method stub
System.out.println("tostring");
return "tostring";
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
System.out.println("hashcode");
return 0;
}
}
为什么它两次调用toString方法? 在什么时候调用哈希码,并且hashcode()调用tostring()或被toString()调用?
不要在toString()
方法中进行System.out.println(...)
调用,因为这没有任何意义。 此方法的目标不是打印字符串,而是返回字符串,调用者可以随后决定该字符串做什么,包括打印出来或在GUI中显示它,等等。
所以改变这个:
public String toString() {
System.out.println("tostring");
return "tostring";
}
对此:
public String toString() {
return "tostring";
}
顺便说一句,System.out.println方法会在要打印的对象上自动调用toString()
,因此无需从method参数内部显式调用此方法。
因此,您可以更改此设置:
System.out.println(obj1.toString());
更简洁:
System.out.println(obj1);
另外,您打算更改您的hashCode()
方法,对吗?
关于,
在什么时候调用哈希码,并且hashcode()调用tostring()还是被toString()调用?
您的程序应准确告诉您何时调用hashCode()
,因为您的重写中包含println。 如果将对象放置在HashSet中或将其用作HashMap的键,则将调用该方法。 检查集合中的相等性时也使用它(我相信),但是请测试您的代码以查看何时和何处使用它。 还可以通过使hashCode返回非0值来使hashCode更加有用,该值取决于类的键字段的状态,即equals
方法测试中使用的相同字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.