Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

As a general rule, use the Object.equals() method to check whether two objects have equivalent contents and use the equality operators == and != to test whether two references specifically refer to the same object.   This latter test is referred to as referential equality. Also see MET09-J. Classes that define an equals() method must also define a hashCode() method .

...

Performance issues can arise because the Java Language Specification provides few guarantees about the implementation of String.intern(). For example:,

  • The cost of String.intern() grows as the number of intern strings grows. Performance should be no worse than n log n, but the Java Language Specification lacks a specific performance guarantee.
  • In early Java Virtual Machine (JVM) implementations, interned strings became immortal: they were exempt from garbage - collection. This can be problematic when large numbers of strings are interned. More recent implementations can garbage-collect the storage occupied by interned strings that are no longer referenced. However, the Java Language Specification lacks any specification of this behavior.
  • In JVM implementations prior to Java 1.7, interned strings are allocated in the permgen storage region, which is typically much smaller than the remainder of the heap. Consequently interning large numbers of strings can lead to an out-of-memory condition. In many Java 1.7 implementations, interned strings are allocated on the heap, thus relieving this restriction. Once again, the details of allocation are unspecified by the Java Language Specification; consequently, implementations may vary.

When canonicalization of objects is required, it may be wiser to use a custom canonicalizer built on top of ConcurrentHashMap; see Joshua Bloch's Effective Java, second edition, Item 69 [Bloch 2008] Item 69 for , for details.

Applicability

Using reference equality to compare objects can lead to unexpected results.

...

Related Guidelines

MITRE CWE

CWE ID 595, " Comparison of Object References Instead of Object Contents"

 

object references instead of object contents
CWE ID 597, " Use of Wrong Operator in String Comparison"wrong operator in string comparison

[Rogue 2000]

Rule 79: , Use equals(), not ==, to test for equality of objects

...

...