Why arrayList.contains() returns false for this usecase where as System.out.print() writes same on console ?
ArrayList<Float> random = new ArrayList<Float>();
random.add(2f);
random.add(4f);
random.add(5f);
random.add(10f);
random.add(99.9f);
System.out.println(random.contains(5.0)); -- this returns false
Where as,
System.out.println(random.get(2)); -- this returns 5.0
In Java, a literal decimal is a double, ie 5.0 is a double.
The contains() method expects an Object (not a primitive, such as double), so Java autoboxes the double to a Double wrapper object, so your test is as if you have coded this:
System.out.println(random.contains(new Double(5.0))); -- always false
Because they are different types, a Double is never going to be equal to a Float, so it's always going to be false.
However, you can code a literal float, add an F (or an f) after the literal.
Try this:
System.out.println(random.contains(5.0F));
I think this is because you are comparing two floats with doubles, 5.0 is a double. But could also be two different references. In which case this discussion may help you: Java List.contains(Object with field value equal to x)
I wanted to test if infinity is equal to infinity in Java:
Double.POSITIVE_INFINITY == Double.POSITIVE_INFINITY
I was surprised by the result when it turned out to be true. My question is how can two infinite values be equal?
Because Double.POSITIVE_INFINITY represents a specific number, so comparing it to itself using == should return true.
This behaviour is specified explicitly in JLS Sec 15.21.1:
Floating-point equality testing is performed in accordance with the rules of the IEEE 754 standard:
...
Otherwise, two distinct floating-point values are considered unequal by the equality operators.
In particular, there is one value representing positive infinity and one value representing negative infinity; each compares equal only to itself, and each compares unequal to all other values.
I'm porting a Java app to C# that makes use of
double x;
if (x == null) blah blah
doubles in .Net aren't nullable so this needs to be changed. No big deal.
It is poor practice to test floating point numbers for equality. So if I initialize a variable
double d = double.MaxValue;
and later want to test it
if (d == double.MaxValue) blah blah
is this valid? Am I guaranteed that the test will always return true, assuming d has not been given a new value?
Double in Java is nullable, since it's a class and therefore a reference type, which boxes a double. You should use Nullable<double> or double? in C# (both are technically the same). Nullable<T> is a generic "box wrapper" for .NET value types.
There's nothing wrong with checking floating point values against some constant that you assigned before.
The smelly part about floats and equality comparison is trying to compare computed values or a computed value and a constant - that will likely fail due to rounding errors.
What is an elegant, readable and non-verbose way of comparing two floating point value for exact equality?
As simple as it may sound, its a wicked problem. The == operator doesn't get the job done for NaN and also has special treatment for zero:
(+0.0 == -0.0) -> true
Double.NaN == Double.NaN -> false
But I want to determine if two values are exactly the same (but I do not care for different NaN patterns, so any NaN == any other NaN -> true).
I can do this with this ugly Monster piece of code:
Double.doubleToLongBits(a) == Double.doubleToLongBits(b)
Is there a better way to write this (and make the intent obvious)?
You can use
Double.compare(a, b) == 0
From the javadoc for compareTo
Double.NaN is considered by this method to be equal to itself and greater than all other double values (including Double.POSITIVE_INFINITY).
0.0d is considered by this method to be greater than -0.0d.
What you've got is already the best way of doing it, I'd say. It makes it clear that you're interested in the bitwise representation of the value. You happen to be converting those bits to long as a convenient 64-bit type which doesn't have any funky behaviour.
If you don't want it appearing frequently in your codebase, just add a method to wrap it:
public static boolean bitwiseEqualsWithCanonicalNaN(double x, double y) {
return Double.doubleToLongBits(x) == Double.doubleToLongBits(y);
}
Note that as per your question, this does not differentiate between different NaN values. If you wanted to do this at a later date, you'd need to use Double.toRawLongBits.
I have been told to never use == for strings but for everything else because .equals would compare the values rather than the instances of the object. (Which I understand the difference of).
According to some sites, == compares memory locations?
What I don't understand is if you're comparing an integer with another, why would it compare memory locations, or is this just for strings?
If you're comparing int 3 to int 4 obviously it wouldn't be in the same memory location, but then if you're comparing int 4 to int 4, does that mean all integers with the value of 4 is stored in the same memory location?
According to some sites, == compares memory locations?
The expression a == b compares the content of a and b, regardless of their types.
What I don't understand is if you're comparing an integer with another, why would it compare memory locations, or is this just for strings?
In case a and b are references, the == operator will compare "memory locations" since that is what the variables contain.
In case a and b are of primitive types, such as int or double the variables will contain actual values, consequently these values (and not their locations) will be compared.
(Note that a variable can never contain an object such as a String, it can at most point at an object.)
Does that mean all integers with the value of 4 is stored in the same memory location?
No. As explained above, ints are compared "directly". When it comes to Integer the story is slightly different. First of all new guarantees that you get hold of a fresh reference, that is
Object i = new Integer(5);
Object j = new Integer(5);
... i == j ...
will always yield false.
If you go through auto-boxing however:
Object i = (Integer) 5;
Object j = (Integer) 5;
... i == j ...
you'll get true due to the fact that auto-boxing goes through a cache for values in the range -128-127. (See for instance this question: Compare two Integer: why is == true?)
== compares the values of the oparands whether it is primitive or reference type.
If the operands are primitive the values of the operands will be compared.
Operands which are references contains values i.e. address to access the object they are referring to. String are not primitive data type, they are considered as objects in java, When you are comparing two references of type string, the result will be true only when the values of the operands i.e. address of the String objects are equal ( which means they refer to the same String object).
Simply put: the thing is that int is a primitive type whereas String is an object. The values of primitive types can be compared with == since the variable points to the value itself rather than the reference to the value.
int's are primitive types in java and as such they don't represent an object "reference" but the value directly.
== compares reference types. int is a primitive type.
so:
int x = 3;
int y = 3;
x==y is true
but using the Integer reference type
Integer x = new Integer(3);
Integer y = new Integer(3);
x == y is false
The == operator compares the references of objects in memory and Strings are objects - primitives aren't objects so as long as they are of the same type, then == will work. As you say, if they are the object variants of primitives (e.g. Integer for int) then java (>5) autoboxes in order to do the compare.
From the Java Specification 15.21 Equality Operators:
15.21 Equality Operators
The equality operators are syntactically left-associative (they group
left-to-right), but this fact is essentially never useful; for
example, a==b==c parses as (a==b)==c. The result type of a==b is
always boolean, and c must therefore be of type boolean or a
compile-time error occurs. Thus, a==b==c does not test to see whether
a, b, and c are all equal.
EqualityExpression:
RelationalExpression
EqualityExpression == RelationalExpression
EqualityExpression != RelationalExpression The == (equal to) and the!= (not equal to) operators are analogous to the relational
operators except for their lower precedence. Thus, a
In all cases, a!=b produces the same result as !(a==b). The equality
operators are commutative if the operand expressions have no side
effects.
15.21.1 Numerical Equality Operators == and !=
If the operands of an equality operator are both of numeric type, or
one is of numeric type and the other is convertible (§5.1.8) to
numeric type, binary numeric promotion is performed on the operands
(§5.6.2). If the promoted type of the operands is int or long, then an
integer equality test is performed; if the promoted type is float or
double, then a floating-point equality test is performed. Note that
binary numeric promotion performs value set conversion (§5.1.13) and
unboxing conversion (§5.1.8). Comparison is carried out accurately on
floating-point values, no matter what value sets their representing
values were drawn from.
Floating-point equality testing is performed in accordance with the
rules of the IEEE 754 standard:
If either operand is NaN, then the result of == is false but the
result of != is true. Indeed, the test x!=x is true if and only if the
value of x is NaN. (The methods Float.isNaN and Double.isNaN may also
be used to test whether a value is NaN.) Positive zero and negative
zero are considered equal. Therefore, -0.0==0.0 is true, for example.
Otherwise, two distinct floating-point values are considered unequal
by the equality operators. In particular, there is one value
representing positive infinity and one value representing negative
infinity; each compares equal only to itself, and each compares
unequal to all other values. Subject to these considerations for
floating-point numbers, the following rules then hold for integer
operands or for floating-point operands other than NaN: The value
produced by the == operator is true if the value of the left-hand
operand is equal to the value of the right-hand operand; otherwise,
the result is false. The value produced by the != operator is true if
the value of the left-hand operand is not equal to the value of the
right-hand operand; otherwise, the result is false.
15.21.2 Boolean Equality Operators == and !=
If the operands of an equality operator are both of type boolean, or
if one operand is of type boolean and the other is of type Boolean,
then the operation is boolean equality. The boolean equality operators
are associative. If one of the operands is of type Boolean it is
subjected to unboxing conversion (§5.1.8).
The result of == is true if the operands (after any required unboxing
conversion) are both true or both false; otherwise, the result is
false.
The result of != is false if the operands are both true or both false;
otherwise, the result is true. Thus != behaves the same as ^
(§15.22.2) when applied to boolean operands.
15.21.3 Reference Equality Operators == and !=
If the operands of an equality operator are both of either reference
type or the null type, then the operation is object equality. A
compile-time error occurs if it is impossible to convert the type of
either operand to the type of the other by a casting conversion
(§5.5). The run-time values of the two operands would necessarily be
unequal.
At run time, the result of == is true if the operand values are both
null or both refer to the same object or array; otherwise, the result
is false.
The result of != is false if the operand values are both null or both
refer to the same object or array; otherwise, the result is true.
While == may be used to compare references of type String, such an
equality test determines whether or not the two operands refer to the
same String object. The result is false if the operands are distinct
String objects, even if they contain the same sequence of characters.
The contents of two strings s and t can be tested for equality by the
method invocation s.equals(t). See also §3.10.5.
The == operator compares ints by value and objects by address. Thus, == is correct for ints but (usually) not for Strings.
Note that if you know that both Strings have been returned by the String.intern method, == works correctly, as intern is guaranteed to return the same address for identical strings.
Objects are equality by value, but the value that objects have is a reference to the memory location. Primitives (i.e. int, boolean, char, double) do not use references, but store their value. So when == is used, it compares the value of the two. In the case of objects it's a reference; however, in the case of primitives it is the value it stores.