Why doesn't my equality comparison using = (a single equals) work correctly in Java?
You should compare (==
) instead of assigning (=
). It can be very dangerous! To avoid such situations you can use Yoda notation
so instead of comparing
address1.compareTo(address2) == 1
You can compare:
1 == address1.compareTo(address2)
In case of missing =
, there will be comparation error.
In your case, it would be better to compare:
address1.compareTo(address2) > 0
Why does non-equality check of one variable against many values always return true?
Use &&
/AND
/and
, not ||
/OR
/or
:
v != "x" && v != "y" && v != "z"
Problem
If an if
block is always executed, the condition for the if block always evaluates to true
. The logical expression must be wrong.
Let us consider v != "x" || v != "y" || v != "z"
for each value of v
.
When
v = "x"
,v != "x"
becomes"x" != "x"
, which is false.v != "y"
becomes"x" != "y"
, which is true.v != "z"
becomes"x" != "z"
, which is true.The expression evaluates to
false || true || true
, which is true.When
v = "y"
, the expression becomes"y" != "x" || "y" != "y" || "y" != "z"
or
true || false || true
, which is true.When
v = "z"
, the expression becomes"z" != "x" || "z" != "y" || "z" != "z"
or
true || true || false
, which is true.For any other value for
v
, the expression evaluates totrue || true || true
, which is true.
Alternatively, consider the truth-table:
│ A B C │
v │ v != "x" v != "y" v != "z" │ A || B || C
───────┼──────────────────────────────────┼──────────────
"x" │ false true true │ true
"y" │ true false true │ true
"z" │ true true false │ true
other │ true true true │ true
As you can see, your logical expression always evaluates to true
.
Solution
What you want to do is, find a logical expression that evaluates to true
when
(v is not "x")
and
(v is not "y")
and
(v is not "z")
.
The correct construction is,
for C-like languages (eg. c#, javascript-(may need the strict equality operator
!==
), php)if (v != "x" && v != "y" && v != "z")
{
// the statements I want to be executed
// if v is neither "x", nor "y", nor "z"
}for Pascal-like languages plsql
IF (v != 'x' AND v != 'y' AND v != 'z') THEN
-- the statements I want to be executed
-- if v is neither "x", nor "y", nor "z"
END IF;
De Morgan's law
By De Morgan's law, the expression can also be rewritten as (using C-like syntax)
!(v == "x" || v == "y" || v == "z")
meaning
not
((v is "x")
or
(v is "y")
or
(v is "z"))
.
This makes the logic a bit more obvious.
Specific languages
Some languages have specific constructs for testing membership in sets, or you can use array/list operations.
sql:
v NOT IN ('x', 'y', 'z')
javascript:
["x", "y", "z"].indexOf(v) == -1
python:
v not in {"x", "y", "z"}
java:
!Arrays.asList("x", "y", "z").contains(v)
java-9 (and above):
!Set.of("x", "y", "z").contains(v)
Why does == not work while comparing two object type variables boxed with same int value
There are two reasons:
Equals
is not bounded with==
and vice versa, and by default checks for reference-equality:As you can read in the specifications of
.Equals
vs==
:By default, the operator
==
tests for reference equality by determining if two references indicate the same object, so reference types do not need to implement operator==
in order to gain this functionality. When a type is immutable, meaning the data contained in the instance cannot be changed, overloading operator==
to compare value equality instead of reference equality can be useful because, as immutable objects, they can be considered the same as long as they have the same value. Overriding operator==
in non-immutable types is not recommended.Overloaded operator
==
implementations should not throw exceptions. Any type that overloads operator==
should also overload operator!=
.Although the compiler will throw an error if you do not override the
!=
as well, and will warn that you better override both.Equals
and.GetHashCode
.So overriding/overloading the
.Equals
,==
and!=
are different things. Overriding.Equals
has no effect on overloading==
and!=
. After all the==
is a custom operator. Although it is not wise to do so, you could use it for another purpose than an equality check.Furthermore operators are resolved at compile-time:
Take the following example the following
csharp
interactive shell program:$ csharp
Mono C# Shell, type "help;" for help
Enter statements below.
csharp> public class Foo {
>
> public int data;
>
> public static bool operator == (Foo f1, Foo f2) {
> return f1.data == f2.data;
> }
>
> public static bool operator != (Foo f1, Foo f2) {
>
> return f1.data != f2.data;
> }
>
> }
(1,15): warning CS0660: `Foo' defines operator == or operator != but does not override Object.Equals(object o)
(1,15): warning CS0661: `Foo' defines operator == or operator != but does not override Object.GetHashCode()
csharp> object f = new Foo();
csharp> object f2 = new Foo();
csharp> f == f2
false
csharp> Foo f3 = f as Foo;
csharp> Foo f4 = f2 as Foo;
csharp> f3 == f4
trueAs you can see,
==
gives a different result if you call the objects asobject
, or asFoo
. Since you use anobject
, the only binding at compile time C# can make is the one with reference equality.
How does the single equal sign work in the if statement in javascript
The first part of your analysis is of course correct.
Now, the interesting part might be why your last code if (var ...) {
doesn't work.
It doesn't work because
1)
var something
is a statement, not an expression.
2) here's how ECMAScript defines the if statement :
IfStatement :
if ( Expression ) Statement else Statement
if ( Expression ) Statement
You must put an expression in the if
clause, not a statement.
More on expressions vs statement in this article.
Why is my Kotlin comparable not makign correct equality comparisons?
Override the equals
function as well, or use a data class
.
compareTo
is only used for the <
and >
operators. The ==
operator is implemented by the separate equals
function.
You can find the available operators, and the functions you need to override for each, in the Operator overloading section of the Kotlin docs.
If you don't override the equals
function, the default behaviour is for it to use object identity. That means that two different objects, even if they contain the same fields, will never be considered equal.
There is however a nice shortcut for what you want to do! Kotlin will automatically generate an equals
function for you if you make your class a data class. It's a good fit for classes like yours, whose main purpose is to hold data.
a single equals in an if. Javascript. Any good reason?
It can be correct.
The code is equivalent to:
jQuery.each(player, function(key, val){
el = $("#pr_attr_plain_"+key);
if (el){
el.text(val === "" ? 0 : " " + val);
}
});
Related Topics
How to Convert Url Parameters to a JavaScript Object
What Is the Shortest Function for Reading a Cookie by Name in JavaScript
Sort Array of Objects by Single Key with Date Value
Why Does [5,6,8,7][1,2] = 8 in JavaScript
Transform Numbers to Words in Lakh/Crore System
Call Static Methods from Regular Es6 Class Methods
How to Get Element by Class Name
What Is Minimum Millisecond Value of Settimeout
Es6 Destructuring Function Parameter - Naming Root Object
Why Does Firebase Lose Reference Outside the Once() Function
Differencebetween Screenx/Y, Clientx/Y and Pagex/Y
When to Use Es6 Class Based React Components VS. Functional Es6 React Components
Find Out Whether Chrome Console Is Open
JavaScript % (Modulo) Gives a Negative Result for Negative Numbers
Javascript: Setting Location.Href Versus Location
Angularjs:Why Ng-Bind Is Better Than {{}} in Angular
Why Does JavaScript Handle the Plus and Minus Operators Between Strings and Numbers Differently