Object 类是一切类的父类, 其中没有成员变量, 仅有方法.

equals()

== 用以判断引用数据类型地址值是否相等.

很多时候需要重写 equals() 来判断两个对象是否相等.

hashcode()

哈希码有两个别名:

  1. 散列码: 为了让对象在内存中不要重叠, 尽量散.
  2. 特征码: 对象的内容的相关体现的码值, 即根据属性值计算的码值. (和MD5码值的机制一样, MD5码值根据文件中的每个字节计数出来).

如果两个对象的 equals()true, 说明两个对象的内容相等, 内容相等就要保证两个对象的特征码必须相等, 体现特征码的特性.

如果两个对象的 equals()false, 说明两个对象的内容不等, 内容不等, 两个对象必须散列, 体现散列性.

如果两个对象的哈希码相等, 说明两个对象的内容相等, equals() 必须为 true;

如果两个对象的哈希码不等, 说明两个对象的内容不等, equals() 必须为 false.

equals() 方法和 hashCode() 方法必须同时出现.

toString()

源码

  1. /**
  2. * Returns a string representation of the object. In general, the
  3. * {@code toString} method returns a string that
  4. * "textually represents" this object. The result should
  5. * be a concise but informative representation that is easy for a
  6. * person to read.
  7. * It is recommended that all subclasses override this method.
  8. * <p>
  9. * The {@code toString} method for class {@code Object}
  10. * returns a string consisting of the name of the class of which the
  11. * object is an instance, the at-sign character `{@code @}', and
  12. * the unsigned hexadecimal representation of the hash code of the
  13. * object. In other words, this method returns a string equal to the
  14. * value of:
  15. * <blockquote>
  16. *
  17. <pre>
  18. * getClass().getName() + '@' + Integer.toHexString(hashCode())
  19. * </pre></blockquote>
  20. *
  21. * @return a string representation of the object.
  22. */
  23. public String toString() {
  24. return getClass().getName() + "@" + Integer.toHexString(hashCode());
  25. }

使用

很多类都重写了 toString() 方法, 创建类时也建议重写.

println(class) 会直接打印对象的 toString() 方法, 且可以规避空指针引用调用 toString() 的问题.

象和字符串拼接时也会自动调用对象的 toString():

  1. Point point1 = new Point(10, 30);
  2. Point point2 = null;
  3. String s2 = "abc";
  4. s2 = s2 + point1 + point2; // abcPoint{x=10, y=30}null

回顾 ==, 比较的是基本数据类型的值和引用数据类型的地址, 计时在多态时, 也是比地址(变量的内容):

  1. Object point = point1;
  2. System.out.println(point == point1); // true

数组的打印

println() 重载了 char 型数组的方法, 即像打印 String 一样直接输出, 具体可以看源码.
public void println(char x[]).

println() 并没有重载 int[]double[] 等数组, 所以调用的还是 println(object o), 调用的是其对象的 toString() 方法, 而数组直接继承于 Object 类, 并未重写 toString() 方法, 所以打印出来是 类名@hashcode.

要想输出数组需要使用相应的工具类 Arrays 的重写的 toString() 方法.

  1. char[] arr = new char[]{'a','b','c'};
  2. System.out.println(arr); // abc
  3. System.out.println(Arrays.toString(arr)); // [a, b, c]
  4. int[] arr1 = new int[]{1,2,3};
  5. System.out.println(arr1); // [I@2530c12
  6. System.out.println(Arrays.toString(arr1)); // [1, 2, 3]
  7. double[] arr2 = new double[]{1.1,2.2,3.3};
  8. System.out.println(arr2); // [D@73c6c3b2
  9. System.out.println(Arrays.toString(arr2)); // [1.1, 2.2, 3.3]