Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if (<object> == <int>)

I can't understand, why the if statement in the picture below returns false. I hope you can explain it to me.

You can see, that the values and the typs of both variables are the same.

enter image description here

like image 518
NelDav Avatar asked Oct 02 '16 11:10

NelDav


People also ask

How do you check if a object is int or not?

Use the int() Method to Check if an Object Is an int Type in Python. We can create a simple logic also to achieve this using the int function. For an object to be int , it should be equal to the value returned by the int() function when this object is passed to it.

How do you check if an object is an int Java?

The instanceof operator is used to determine if the array item is an Integer or a String . For strings, you must first narrow the Object to string (see line 8 in the source code) and then use the parseInt method of the Integer class (line 9).

How do you compare two objects?

The equals() method of the Object class compare the equality of two objects. The two objects will be equal if they share the same memory address. Syntax: public boolean equals(Object obj)

What operator or method is used to compare objects for ordering?

The Comparable interface allows us to define an ordering between objects by determining if an object is greater, equal, or lesser than another. The Comparable interface is generic and has only one method, compareTo(), which takes an argument of the generic type and returns an int.


1 Answers

The == operator you are calling is the overload that takes two object parameters. This uses reference equality - the value isn't important, it has to be the same object.

As you can read in the documentation:

For reference types other than string, == returns true if its two operands refer to the same object. For the string type, == compares the values of the strings.

While int is a value type, it has been 'boxed' (wrapped in an object). You are comparing the two different reference types that wrap your integers.

To fix this, you can use object.Equals instead - this will compare the two integers.

item.Equals(value);

Or the static method (which would handle the case where item == null):

object.Equals(item, value);

If you unbox to int then you can use the int overload of == as you expect:

(int)item == (int)value;

Again, per the docs:

For predefined value types, the equality operator (==) returns true if the values of its operands are equal.

like image 127
Charles Mager Avatar answered Oct 12 '22 04:10

Charles Mager