Why can’t we use ‘==’ to compare two float or double numbers [duplicate]

From apidoc, Float.compare: Compares the two specified float values. The sign of the integer value returned is the same as that of the integer that would be returned by the call: new Float(f1).compareTo(new Float(f2)) Float.compareTo: Compares two Float objects numerically. There are two ways in which comparisons performed by this method differ from those performed … Read more

How to implement hashCode and equals method

in Eclipse right mouse click-> source -> generate hashCode() and equals() gives this: /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (code == null ? 0 : code.hashCode()); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ … Read more

What does comparison being consistent with equals mean ? What can possibly happen if my class doesn’t follow this principle?

Here’s a simple but realistic example of what can happen if a comparison method is inconsistent with equals. In the JDK, BigDecimal implements Comparable but its comparison method is inconsistent with equals. For example: > BigDecimal z = new BigDecimal(“0.0”) > BigDecimal zz = new BigDecimal(“0.00”) > z.compareTo(zz) 0 > z.equals(zz) false This is because … Read more

Is there a complete IEquatable implementation reference?

Implementing IEquatable<T> for a Value Type Implementing IEquatable<T> for a value type is a little bit different than for a reference type. Let’s assume we have the Implement-Your-Own-Value-Type archetype, a Complex number struct. public struct Complex { public double RealPart { get; set; } public double ImaginaryPart { get; set; } } Our first step … Read more

What’s the best way to compare Double and Int?

You really can’t compare floating point and integral values in a naive way; particularly, since there’s the classic floating point representation challenges. What you can do is subtract one from the other and see if the difference between them is less than some precision you care about, like so: int iValue = 0; double dValue … Read more