6.4.对象方法

6.4对象方法

1.对象方法概述

  所有的类都继承了Object类。它们继承的方法如下:

  • 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
2
3
public String toString() {
/* hmmm */
}

  solution

1
2
3
4
5
6
7
8
9
public String toString() {
String returnString = "{";
for (int i = 0; i < size; i += 1) {
returnString += keys[i];
returnString += ", ";
}
returnString += "}";
return returnString;
}

  这种写法看似简洁优雅,但每次使用+=运算符后,都需要创建一个新的字符串,这样的时间复杂度为O(n2)。为了优化该方法,Java内置了StringBuilder方法。这个方法创造一个String的可变对象,我们可以向对象内添加其它String

1
2
3
4
5
6
7
8
9
10
public String toString() {
StringBuilder returnSB = new StringBuilder("{");
for (int i = 0; i < size - 1; i += 1) {
returnSB.append(items[i].toString());
returnSB.append(", ");
}
returnSB.append(items[size - 1]);
returnSB.append("}");
return returnSB.toString();
}

3.equals()

  a.equals()的实现

  在Java中,==检查两个对象在内存中的是否为同一个对象。由之前passbyvalue原则,==会检查两个盒子放的是不是同一个东西:

  • 对于基本类型的变量,这表示比较它们的值是否相等。
  • 对于对象(objects),这表示比较两个对象的地址或指针是否相等。

  而equals()方法在比较对象时,只会比较两者的值是否相等,这便是我们实现它的目的。我们可以如下实现ArraySetequals()方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public boolean equals(Object other) {
if (this == other) {
return true;
}

if (other == null) {
return false;
}

if (other.getClass() != this.getClass()) {
return false;
}

ArraySet<T> o = (ArraySet<T>) other;
if (o.size() != this.size()) {
return false;
}

for (T item : this) {
if (!o.contains(item)) {
return false;
}
}
return true;
}
  在上面的equals()方法中,我们加入了对null与跨类对象的比较的判断。我们也通过预先判断==的情况优化了方法。

  b.equals()方法的规则

  equals()方法要符合以下规则:

  1. 反身性(reflexive):x.equals(x) == true
  2. 对称性(symmetric):x.equals(y) == true当且仅当y.equals(x) == true
  3. 传递性(transitive):x.equals(y), y.equals(z) == true,则x.equals(z) == true
  4. x.equals(null) == false,不论x是什么。
  5. equals()方法的参数必须是object型的,这样才能覆盖原有的.equals()方法。