设计了一个User类,需要重写equals方法(userName相等即认为User对象相等)。重写后用以下代码做了检测,all green ,呵呵 /** * 用于测试User对象的相等性 */ public class TestUserEquals { public static void testEquals() { User objUser1 = new User("zhangsan", "1", "2", "3", "4"); // 自反性:x.equals(x) assert(objUser1.equals(objUser1)); User objUser2 = new User("zhangsan", "2", "2", "3", "4"); // 对称性:a.equals(b) <=> b.equals(a) assert(objUser1.equals(objUser2)); assert(objUser2.equals(objUser1)); User objUser3 = new User("zhangsan", "3", "2", "3", "4"); // 传递性: a.equals(b) && b.equals(c) => a.equals(c) assert(objUser1.equals(objUser2)); assert(objUser2.equals(objUser3)); // 一致性: 对于任意的引用值x 和 y,如果用于equals比较的对象信息没有被修改,多次调用x.equals(y)要么一致地返回true,要么一致地返回false。 assert(objUser1.equals(objUser2)); assert(objUser1.equals(objUser2)); assert(objUser1.equals(objUser2)); assert(objUser1.equals(objUser2)); // 非空性:对于任意的非空引用值x,x.equals(null)一定返回false。 assert(!objUser1.equals(null)); User objNull = null; assert(objNull.equals(null)); User objUser4 = objUser1; // 测试引用 assert(objUser4.equals(objUser1)); User objUser5 = new User("sun", "1", "2", "3", "4"); // 特征测试:strUserName不相等的对象一定不等 assert(!objUser5.getUserName().equals(objUser1.getUserName())); assert(!objUser5.equals(objUser1)); // 特征测试:strUserName相等的对象一定相等 assert(!objUser2.getUserName().equals(objUser1.getUserName())); assert(!objUser2.equals(objUser1)); } public static void testHashCode() { User objUser1 = new User("zhangsan", "1", "2", "3", "4"); User objUser2 = new User("zhangsan", "1", "2", "3", "4"); // 测试,相等的对象拥有相同的hash码 assert(objUser1.equals(objUser2)); assert(objUser1.hashCode() == objUser2.hashCode()); } public static void main(String[] args) { testEquals(); testHashCode(); System.out.println("all green"); } }