String与其他类对象的hashCode

时间:2017-11-29 15:40:40

标签: java hashcode

class Employee {
  String name;

  Employee(String name) {
    this.name = name;
  }
  // hashCode method is not overridden
}

public class HashCodeConfusion {
  public static void main(String[] args) {
    Employee emp = new Employee("ABC");
    Employee emp1 = new Employee("ABC");

    if (emp == emp1) {
      System.out.println("Employee Same reference");
    } else {
      System.out.println("Employee Different reference");
    }
    if (emp.hashCode() == emp1.hashCode()) {
      System.out.println("Employee Same hash code");
    } else {
      System.out.println("Employee Different hash code");
    }

    // -----------------------------------

    String str = new String("ABC");
    String str1 = new String("ABC");

    if (str == str1) {
      System.out.println("String Same reference");
    } else {
      System.out.println("String Different reference");
    }
    if (str.hashCode() == str1.hashCode()) {
      System.out.println("String Same hash code");
    } else {
      System.out.println("String Different hash code");
    }
  }
}

问题/混乱: Object类的默认hashCode似乎考虑了对象引用而不仅仅是内容,为什么具有相同名称的employee类对象会出现不同的哈希代码呢? 如果Object类的默认实现只有一些基于内容的哈希算法,那么只要我的equals范例与按位兼容性一致,就不需要覆盖hashCode方法。

有什么可以清除这种混乱吗?

0 个答案:

没有答案