Object 类是一切类的父类, 其中没有成员变量, 仅有方法.
equals()
== 用以判断引用数据类型地址值是否相等.
很多时候需要重写 equals() 来判断两个对象是否相等.
hashcode()
哈希码有两个别名:
- 散列码: 为了让对象在内存中不要重叠, 尽量散.
- 特征码: 对象的内容的相关体现的码值, 即根据属性值计算的码值. (和MD5码值的机制一样, MD5码值根据文件中的每个字节计数出来).
如果两个对象的 equals() 为 true, 说明两个对象的内容相等, 内容相等就要保证两个对象的特征码必须相等, 体现特征码的特性.
如果两个对象的 equals() 为 false, 说明两个对象的内容不等, 内容不等, 两个对象必须散列, 体现散列性.
如果两个对象的哈希码相等, 说明两个对象的内容相等, equals() 必须为 true;
如果两个对象的哈希码不等, 说明两个对象的内容不等, equals() 必须为 false.
equals() 方法和 hashCode() 方法必须同时出现.
toString()
源码
/*** Returns a string representation of the object. In general, the* {@code toString} method returns a string that* "textually represents" this object. The result should* be a concise but informative representation that is easy for a* person to read.* It is recommended that all subclasses override this method.* <p>* The {@code toString} method for class {@code Object}* returns a string consisting of the name of the class of which the* object is an instance, the at-sign character `{@code @}', and* the unsigned hexadecimal representation of the hash code of the* object. In other words, this method returns a string equal to the* value of:* <blockquote>*<pre>* getClass().getName() + '@' + Integer.toHexString(hashCode())* </pre></blockquote>** @return a string representation of the object.*/public String toString() {return getClass().getName() + "@" + Integer.toHexString(hashCode());}
使用
很多类都重写了 toString() 方法, 创建类时也建议重写.
println(class) 会直接打印对象的 toString() 方法, 且可以规避空指针引用调用 toString() 的问题.
象和字符串拼接时也会自动调用对象的 toString():
Point point1 = new Point(10, 30);Point point2 = null;String s2 = "abc";s2 = s2 + point1 + point2; // abcPoint{x=10, y=30}null
回顾 ==, 比较的是基本数据类型的值和引用数据类型的地址, 计时在多态时, 也是比地址(变量的内容):
Object point = point1;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() 方法.
char[] arr = new char[]{'a','b','c'};System.out.println(arr); // abcSystem.out.println(Arrays.toString(arr)); // [a, b, c]int[] arr1 = new int[]{1,2,3};System.out.println(arr1); // [I@2530c12System.out.println(Arrays.toString(arr1)); // [1, 2, 3]double[] arr2 = new double[]{1.1,2.2,3.3};System.out.println(arr2); // [D@73c6c3b2System.out.println(Arrays.toString(arr2)); // [1.1, 2.2, 3.3]
