[关闭]
@w1024020103 2017-01-25T12:02:52.000000Z 字数 879 阅读 668

equals方法

Java equals


equals方法

Object类中定义有:

public boolean equals(Object obj)方法

提供定义对象是否”相等“的逻辑。

Object的equals方法定义为: x.equals(y)当x和y是同一个对象时返回true否则返回false

JDK提供的一些类,如String,Date等,重写了Object的equals方法,调用这些类的equals方法,x.equals(y),当x和y所引用的对象是同一类对象且属性内容相等时(并不一定是相同对象),返回true否则返回false.

可以根据需要在用户自定义类型中重写equals方法.

(bjsxt)

When doing coursera Algorithem week4 assignment and determining whether two 3-3 boards are equal, I wrote codes like this:

  1. public boolean equals(Object y){ // does this board equal y?
  2. if (y == this) return true; //check out Transaction.java and imitate
  3. if (y == null) return false;
  4. if (y.getClass() != this.getClass()) return false;
  5. Board that = (Board) y;
  6. if(this.dimension() != that.dimension()) {
  7. return false;
  8. }
  9. //return (this.board == that.board) && (this.n == that.n); this could be reference equal
  10. for(int i = 0; i<n; i++){
  11. for(int j = 0; j< n; j++) {
  12. if (this.board[i][j] != that.board[i][j]) {
  13. return false;
  14. }
  15. }
  16. }
  17. return true;
  18. }

This brought me to take a deeper look at the equals method.

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注