編寫equals 的建議:
1.測試this與otherobject是否是同一對象
if (this==otherobject) return true;
2.測試otherobject是否爲null.如果是,就返回false.
if (otherobject==null) return false;
3.測試this和otherobject是否同屬於一個類
if (getclas()!=otherobject.getclass()) return false;
4. 把otherobject的類型轉換爲你的類所屬的類型
ClassName other=(ClassName)otherobject
5.比較所有字段.使用==比較基本類型字段,使用equals比較對象字段
return fields1==other.fields && field2.equals(other.field2)&&............
tostring 方法
object的另一個重要方法就是tostring ,它返回一個代表該對象值字符串.
大多數(不是全部)tostring 方法都遵循如下格式:類名,然後在方括號中列舉個字段的值.
無論何時對象與字符串相連接,那麼就可以使用"+"操作符,這時JAVA編譯器會自動調用tostring 方法獲得對象的字符串表示.