Home>

First look,Such as the following code:

int age=25;
short newage=25;
console.writeline (age == newage);//true
console.writeline (newage.equals (age));//false
console.readline ();

int and short are primitive types,But comparison with "==" returns true, and comparison with equals () returns false.why?

In short:"equals ()" is more complicated than "=".

Specifically:

The primitive type overrides the object.equals (object) of the base class, and returns true when the object in the parentheses is the same as its type and value (note that the nullable type is also suitable for the above judgment;Non-nullable types are always boxed to an instance of the underlying type).

NewBecause newage is short, when the object is short and the value is equal to the newage value,newage.equals (object) returns true. You are passing an int object, so it returns false.

In contrast,The "==" operator is defined as an operation with two integers (int) or two short integers (short) or two long integers (long). When the "==" two parameters are an integer and a short integer,The compiler implicitly converts short to int and compares the size of the int value after conversion.

Other ways to make it work:

Primitive types also have their own equals () method, and equals accepts parameters of the same type.

If you write age.equals (newage), the compiler will choose int.equals (int) as the best overload method and implicitly convert short to int. It then returns true because this method directly compares the size of two int values.

Short also has a short.equals (short) method, but the int type cannot be implicitly converted to short, so it will not be called.

You can force this method using the cast conversion:

console.writeline (newage.equals ((short) age));//true

This will call short.equals (short) directly without boxing.If age is greater than 32767, it will throw an overflow exception.

You can also call short.equals (object) overload,But you need to explicitly pass a boxed object of the same type:

console.writeline (newage.equals ((object) (short) age));//true

Like the previous optional method (short.equals (short)), if the size exceeds the short range, an overflow exception is also thrown.Different from previous solutions,It short-boxes into an object—a waste of time and memory.

Here is equals () used in practice:

public override bool equals (object obj) {
    if (! (obj is int16)) {
      return false;
    }
    return m_value == ((int16) obj) .m_value;
  }
  public bool equals (int16 obj)
  {
    return m_value == obj;
  }
c
  • Previous AngularJS basic ng-if instruction usage
  • Next Example of jQuery simple title hint effect