6.4.对象方法
对象方法
1.对象方法概述
所有的类都继承了
- String toString()
- boolean equals(Object obj)
- Class <?> getClass()
- int hashCode()
- protected Objectclone()
- protected void finalize()
- void notify()
- void notifyAll()
- void wait()
- void wait(long timeout)
- void wait(long timeout, int nanos)
下面我们重点讨论前两个。
2.toString()
toString
方法返回一个对象的字符串表示。对于特定的类,我们可以覆盖对象原有的方法。考虑下面的问题:
Exercise 6.4.1: Write the toString() method so that when we print an ArraySet, it prints the elements separated by commas inside of curly braces. i.e {1, 2, 3, 4}. Remember, the toString() method should return a string:
1 | public String toString() { |
1 | public String toString() { |
这种写法看似简洁优雅,但每次使用+=
运算符后,都需要创建一个新的字符串,这样的时间复杂度为StringBuilder
方法。这个方法创造一个
1 | public String toString() { |
3.equals()
equals()
的实现
在==
检查两个对象在内存中的是否为同一个对象。由之前==
会检查两个盒子放的是不是同一个东西:
- 对于基本类型的变量,这表示比较它们的值是否相等。
- 对于对象(
),这表示比较两个对象的地址或指针是否相等。
而equals()
方法在比较对象时,只会比较两者的值是否相等,这便是我们实现它的目的。我们可以如下实现equals()
方法:
1 | public boolean equals(Object other) { |
equals()
方法中,我们加入了对==
的情况优化了方法。
equals()
方法的规则
equals()
方法要符合以下规则:
- 反身性(
):x.equals(x) == true
。 - 对称性(
):x.equals(y) == true
当且仅当y.equals(x) == true
。 - 传递性(
):x.equals(y), y.equals(z) == true
,则x.equals(z) == true
。 x.equals(null) == false
,不论 是什么。equals()
方法的参数必须是 型的,这样才能覆盖原有的.equals()
方法。
Related Issues not found
Please contact @fyerfyer to initialize the comment