当前位置: 动力学知识库 > 问答 > 编程问答 >

Multiple uses of "this" keyword in Java

问题描述:

So, I have this. It compares two card decks and if they are the same the result is true.

public boolean equals ( Object obj ) {

boolean result = true;

for (int i = 0; i < 52; i++) {

if (this.cardAt(i) = this2.cardlist(i)) {

result = true;

} else {

result = false;

}

}

}

I would like to be able to compare two random card decks, if you will.

But I don't know how to compare two different ones using "this .

I simply wrote "this2" to replace another instance of "this".

What could I do to replace this "this2" to still be able to compare two card decks?

网友答案:

obj is your this2

Consider this adaptation:

public boolean equals ( Object obj) {
      if(!obj instanceof Deck) return false; // make sure you can cast
      Deck otherDeck = (Deck)obj // make the cast
      for (int i = 0; i < 52; i++) {
          if (!this.cardAt(i).equals(otherDeck.cardAt(i)) // use .equals() instead of ==
            return false; // return false on the first one that's wrong
      }
      return true;

 }

Your old method would have been flawed. Let's say there's a 4 card deck: { 4S, 3C, 5D, AH } And another 4 card deck { 4S, 10C, 5D, AH}

Walk through them

result = true
current index 0... compare 4S to 4S... good, so...
result = 4S == 4S ? true
result = 3C == 10C ? false
result = 5D == 5D ? true
result = AH == AH ? true

So your method only tests if the LAST card is correct. (Also it never returns when you're done!)

网友答案:

You would cast obj to the type of class you are currently in, like so

MyClass other = (MyClass)obj;
// Now do calculations using  other  instead of  this2.
网友答案:
public boolean equals ( Object obj )
{
     boolean result = false; // No need of result variable
     for (int i = 0; i < 52; i++) {
         if (this.cardAt(i) == obj.cardlist(i)) // not = , it should be ==
         {
              return true;
         } 
     }
     return false;
}

Edit 1: However, this logic do not traverse the entire cardlist. Just tests whether the corresponding cards are equal or not. If found at least one match, it returns leaving the rest of cards to be compared, else traverses the entire list.

分享给朋友:
您可能感兴趣的文章:
随机阅读: