How does the toString(), ==, equals() object methods work differently or similarly on reference and primitive types?

后端 未结 3 774
不知归路
不知归路 2020-12-11 04:49

How does the toString() method, == operator, and equals() method work differently or similarly on reference and primitive types?

3条回答
  •  离开以前
    2020-12-11 05:36

    The '==' operator works on the primitive type you have, that in the case of reference objects is the reference itself. That is a == b will compare the values for primitive types as int, but will compare the reference (not the value) for reference types. Two objects of reference type that are not the same but have the same value will return true when the equals() method is called, but a == b will be false.

    For primitive types, when calling a method, the type is previously converted (boxed) to a reference type and then the method is called. This means that for primitive types a == b will yield the same value as a.equals(b), but in the latter case two temporary boxed objects are created prior to calling the equals() method. This will make the operation more expensive in CPU time which may or may not be a problem depending on where it happens.

    That is, to compare primitive type values you should use ==, while to compare reference type values you should use the .equals() method.

    The same happens with the toString() method. When called on a reference type object, it will call the appropriate method and produce a String. When called on a primitive type, the type will be autoboxed and then the method will be called in the temporary object. In this case, you can call the appropriate toString() static method (i.e. for int call Integer.toString( myint )) this will avoid creating the temporary object.

提交回复
热议问题