package com.test; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Test x=new Test("x"); Test y=new Test("y"); System.out.println("x HashCode="+x.hashCode()); System.out.println("y HashCode="+y.hashCode()); System.out.println(x.equals(y)==true); } } class Test{ private String name; public Test(String name){ this.name=name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { return true; } }
x HashCode=151 y HashCode=152 true
所以这个面试题是可以的
两个对象值相同(x.equals(y) == true),但却可有不同的hash code,这句话对不对?
原文地址:http://blog.csdn.net/whzhaochao/article/details/41115343