通常,在Java/C#中对引用类型变量使用==相等时?

7 c# java

作为对"等于和==之间的差异"的问题的一种跟进:在什么样的情况下,你会发现自己在Java/C#中测试参考相等性?

Ber*_*t F 6

巩固答案......

通常,在Java/C#中对引用类型变量使用==相等时?

1.检查null:

if (a == null) ...
Run Code Online (Sandbox Code Playgroud)

2.在构建equals实现时提高效率:

boolean equals(Object o) {
    if (o == null)      return false;
    if (this == o)      return true;

    // Some people would prefer "if (!(o instanceof ClassName)) ..."
    if (getClass() != o.getClass())   return false;

    // Otherwise, cast o, leverage super.equals() when possible, and
    // compare each instance variable ...
Run Code Online (Sandbox Code Playgroud)

3.为了提高效率,比较枚举或比较设计的类的对象,以便比较对象标识等同于检查对象等价(例如,类对象):

enum Suit { DIAMONDS, HEARTS, CLUBS, SPADES }

class SomeCardGame {
    ...
    boolean static isATrumpCard(Card c) {
        return (c.getSuit() == TRUMP_SUIT);
    }
}
Run Code Online (Sandbox Code Playgroud)

4.当你真的打算检查对象标识,而不是对象等价时,例如一个想要确保一个类没有放弃对内部数据结构实例的引用的测试用例.

boolean iChoseNotToUseJUnitForSomeReasonTestCase() {
    final List<String> externalList = testObject.getCopyOfList();
    final List<String> instanceVariableValue =
        getInstanceVariableValueViaCleverReflectionTrickTo(testObject, "list");
    if (instanceVariableValue == externalList) {
      System.out.println("fail");
    } else {
      System.out.println("pass");
    }
}
Run Code Online (Sandbox Code Playgroud)

有趣的是,对于第3点,一篇文章建议使用equals 比使用.equals()更安全,因为如果您尝试比较不属于同一类的对象引用,编译器会抱怨(http://schneide.wordpress.com/2008/09/22 /或 - 等于/).


Yis*_*hai 5

对于Java,最常见的是查看引用是否为null:

 if (someReference == null) {
 //do something
 }
Run Code Online (Sandbox Code Playgroud)

它在enums中也很常见,但是我见过的最常用的是使用正确实现的equals方法.第一个检查将检查引用相等性,如果返回false,则仅执行更昂贵的计算.


z *_* - 1

您可以使用它进行快速相等性检查。

例如,如果您正在与一些可能需要一段时间才能迭代的非常大的对象进行比较,您可以节省时间来首先查看它们是否引用同一个对象

Compare(LargeObj a, LargeObj b) {
if (a == b)
  return true;

// do other comparisons here

}
Run Code Online (Sandbox Code Playgroud)