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.
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.
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).
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)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With