I am trying to create an equals() method for a class and I am getting the following error for the last three lines of my "if statement": double cannot be derefferenced. modelName and VINumber are inherited properties. Can someone tell me what I am doing wrong here?
public boolean equals(FourByFour f){
boolean status = false;
if (VINumber.equals(f.VINumber) &&
modelName.equals(f.modelName) &&
bayWidth.equals(f.bayWidth) &&
bayHeight.equals(f.bayHeight) &&
bayLength.equals(f.bayLength))
{
status = true;
}
return status;
}
Sample Code
double z=100,x=100;
System.out.println("z == x : "+ (z == x));
Double Z = new Double(z), X = new Double(x);
System.out.println("Z.equals(X) : "+ Z.equals(X)+"\n(Z==X) : "+(Z==X));
Output :
z == x : true
Z.equals(X) : true
(Z==X) : false
I hope this example makes things much clearer.
You can't use .equals when using primitives (e.g. double) as the data type.
The only operators that can be used are ==, !=, <, <=, >, >=.
These will give you the boolean results of the comparisons they represent on the basis of the value of the primitive variable.
However, if you use Autoboxing by using the java wrapper classes for primitive types, then .equals will give you the arithmetic comparison of your data types, whereas == will compare the variable addresses.
Presumably bayWidth, bayHeight, and bayLength are doubles. doubles are primitives, not reference types, and have no methods. Use java.lang.Double.compare to compare double primitives for equals methods.
simply you can only compare object variable like String with .equals
if you look on .equals method documentation:
public boolean equals(Object anObject)
Parameters:
anObject − the object to compare this String against.
so you can't use this method to compare other primitive datatype like double, float or int because they are not object variables.
you should compare them with == operator
or you can use Double class constructor to convert double primitive type to a Double object:
Double bayWidthobj = new Double(bayWidth);
Double bayHeightobj = new Double(bayHeight);
Double bayLengthobj = new Double(bayLength);
Related
As we know that == in case of Objects returns true if pointing to the same reference else it returns false.
So , if i have taken
Integer a = new Integer("1"); // Creating Integer Object a
Integer b = new Integer("1"); // Creating Integer Object b
and then perform a == b , then it returns true
but they both have different references.
The JVM caches integer values between -127 to 127.
That's the reason == works for Integer value between this range.
But:
Integer i1=new Integer("11");
Integer i2=new Integer("11");
System.out.println(i1==i2); //false
Integer i3=11;
Integer i4=11;
System.out.println(i3==i4); //true
Integer i5=128;
Integer i6=128;
System.out.println(i5==i6); //false
Because it is overridden. source:
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
Let me more elaborate on this, #asAmit Bhati said in his answer when we write
Integer i1=new Integer("11");
Integer i2=new Integer("11");
System.out.println(i1==i2); //false
jvm creates two separate objects and comparing them with "==" results in false. but when we write the following code:
Integer i3=11;
Integer i4=11;
System.out.println(i3==i4); //true
it will be translated into this:
Integer i3=Integer.valueOf(11);
Integer i4=Integer.valueOf(11);
Implementation of valueOf method is as follow(in java 1.8):
public static Integer valueOf(int var0) {
return var0 >= -128 && var0 <= Integer.IntegerCache.high?Integer.IntegerCache.cache[var0 + 128]:new Integer(var0);
}
as you can see if the value is between -128 and Maximum cache value (which can be configured using this jvm parameter -Djava.lang.Integer.IntegerCache.high), it will retrieve the cached value and doesn't create a new instance of Integer that is why (==) returns true for certain values!
also note that the same goes for Character Wrapper class but not for Float and Double classes.
As the answer above says, it may work in many cases, nevertheless you shouldn't compare two Integer with == since it may present problems in some cases.
Check this answer for more information:
Comparing Integer values in Java, strange behavior
If you check equals method implementation in Integer class it is:
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
From here you can see it uses "==" operator.
Now the reason behind it. Ultimately you have to compare value of the Integer wrapper class, which will happen automatically because of autoboxing and unboxing in Java.
And also from the method definition you can see that it is retrieving passed Object value using ((Integer)obj).intValue().
Java operator == is used for reference comparison
then how can == be used for comparing int a =1; and int b = 1;
both values are stored in different locations then how it compares
As commented by Andy, the JLS states that the operator '==' is indeed used for reference type comparison but also for numeric type and Boolean type comparison.
int is a numeric type.
When comparing numeric types the values are compared (not the references).
However if you want to determine if the references of two integers are equal rather than the values then you can use the Integer class. This class simply wraps the primitive numeric type int.
Now consider the following code:
public class TestClass {
public static void main(String[] args)
{
Integer A = new Integer(1);
Integer B = new Integer(1);
Integer C = A;
if (A == B) System.out.println("Won't print."); // (1)
if (A.equals(B)) System.out.println("WILL Print!!!"); // (2)
if (A == C) System.out.println("WILL Print!!!"); // (3)
}
}
Because A and B are objects, the reference of A is compared to the reference of B. Even though their int values are the same, because they are independent references this statement is false.
The equals method compares the int values of each Integer object and thus is true.
Integer object C references object A. Hence this reference comparison will be true.
This question already has answers here:
Compare two objects with .equals() and == operator
(16 answers)
Closed 7 years ago.
the targetPixValList is a list contains Double objects and it contains also similar values in successive position in the list, and when i tried to compare two Double values using Code_1, the cnt returns zero.
and when i used code_2, the cnt returns value.
and the type of the list is
why "==" operator does not work with Double?
Code_1:
int cnt = 0;
for (int i = 0; i < cs.targetPixValList.size()-1; i++) {
if (cs.targetPixValList.get(i) == cs.targetPixValList.get(i+1))
++cnt;
}
Code_2:
int cnt = 0;
for (int i = 0; i < cs.targetPixValList.size()-1; i++) {
if (cs.targetPixValList.get(i).equals(cs.targetPixValList.get(i+1)))
++cnt;
}
Double is a class wrapper for primitive double. When comparing instances of Double (or object references) use equals method rather than ==.
Also, for your case, the comparison of Double by using equals could also give wrong results due to float point comparison (done behind the scenes). If you're working with sensitive floating points values, I recommend using BigDecimal instead of Double and use BigDecimal#compareTo rather than equals because BigDecimal#equals does not take into account the scale, while BigDecimal#compareTo does.
You use .equals(otherObject) when comparing objects. You're comparing Double which is an object. If you were using double instead, a primitive, you could use == to compare values.
Alternatively, get the double value from Double object:
if (yourDoubleObject.doubleValue() == otherDoubleObject.doubleValue()) {
// Do some things
}
== operator gives correct results in primitive types like int, long, double. If you use the operator with objects it will compare the references by default.
Using equals method may give the correct result dependingof the object. You should override equals method to receive logically check if the objects are equals.
For Double object, ,it also checks the referance equivalence of the objects. You should use Double#doubleValue method to check value equivalence.
Here is the code;
for (int i = 0; i < cs.targetPixValList.size()-1; i++) {
if (cs.targetPixValList.get(i).doubleValue() == cs.targetPixValList.get(i+1).doubleValue())
++cnt;
}
See also :
How to override equals and hashcode
Hi I am revising and understand the difference between equals() and '==' however this code really confuses me:
public class MyTest {
public static void main(String[] args) {
Integer w = new Integer(1);
Integer x = 1;
double z = x;
System.out.println(z == w);
}
}
How can a double object have the same reference as an Integer object in memory when using '==' ? Cannot understand this. Thank you for reading!
If you compare primitive and wrapper using == operator, then the wrapper values will be un boxed and compared with primitive value.
From JLS 15.21.1
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).
A double is not a reference, because it is a primitive type. It is a value instead. Double would have been a reference.
When you write z == w, where z is double-typed and w is Integer-typed, the runtime definitely has to compare something. And, obviously, it has to compare things of the same kind. It will not compare the double value with the Integer reference. Instead, it will unbox the Integer and will compare the int value obtained after unboxing with the double value. Both being 1, the boolean operator will return true.
Here objects are not compared but primitive types are compared with feature of unboxing for Integer.
I have integers that are supposed to be equal (and I verify it by output). But in my if condition Java does not see these variables to have the same value.
I have the following code:
if (pay[0]==point[0] && pay[1]==point[1]) {
game.log.fine(">>>>>> the same");
} else {
game.log.fine(">>>>>> different");
}
game.log.fine("Compare:" + pay[0] + "," + pay[1] + " -> " + point[0] + "," + point[1]);
And it produce the following output:
FINE: >>>>>> different
FINE: Compare:: 60,145 -> 60,145
Probably I have to add that point is defined like that:
Integer[] point = new Integer[2];
and pay us taken from the loop-constructor:
for (Integer[] pay : payoffs2exchanges.keySet())
So, these two variables both have the integer type.
Check out this article: Boxed values and equality
When comparing wrapper types such as Integers, Longs or Booleans using == or !=, you're comparing them as references, not as values.
If two variables point at different objects, they will not == each other, even if the objects represent the same value.
Example: Comparing different Integer objects using == and !=.
Integer i = new Integer(10);
Integer j = new Integer(10);
System.out.println(i == j); // false
System.out.println(i != j); // true
The solution is to compare the values using .equals()…
Example: Compare objects using .equals(…)
Integer i = new Integer(10);
Integer j = new Integer(10);
System.out.println(i.equals(j)); // true
…or to unbox the operands explicitly.
Example: Force unboxing by casting:
Integer i = new Integer(10);
Integer j = new Integer(10);
System.out.println((int) i == (int) j); // true
References / further reading
Java: Boxed values and equality
Java: Primitives vs Objects and References
Java: Wrapper Types
Java: Autoboxing and unboxing
If they were simple int types, it would work.
For Integer use .intValue() or compareTo(Object other) or equals(Object other) in your comparison.
In java numeric values within range of -128 to 127 are cached so if you try to compare
Integer i=12 ;
Integer j=12 ; // j is pointing to same object as i do.
if(i==j)
print "true";
this would work, but if you try with numbers out of the above give range they need to be compared with equals method for value comparison because "==" will check if both are same object not same value.
There are two types to distinguish here:
int, the primitive integer type which you use most of the time, but is not an object type
Integer, an object wrapper around an int which can be used to use integers in APIs that require objects
when you try to compare two objects (and an Integer is an object, not a variable) the result will always be that they're not equal,
in your case you should compare fields of the objects (in this case intValue)
try declaring int variables instead of Integer objects, it will help
The condition at
pay[0]==point[0]
expression, uses the equality operator == to compare a reference
Integer pay[0]
for equality with the a reference
Integer point[0]
In general, when primitive-type values (such as int, ...) are compared with == , the result is true if both values are identical. When references (such as Integer, String, ...) are compared with == , the result is true if both references refer to the same object in memory.
To compare the actual contents (or state information) of objects for equality, a method must be invoked.
Thus, with this
Integer[] point = new Integer[2];
expression you create a new object that has got new reference and assign it to point variable.
For example:
int a = 1;
int b = 1;
Integer c = 1;
Integer d = 1;
Integer e = new Integer(1);
To compare a with b use:
a == b
because both of them are primitive-type values.
To compare a with c use:
a == c
because of auto-boxing feature.
for compare c with e use:
c.equals(e)
because of new reference in e variable.
for compare c with d it is better and safe to use:
c.equals(d)
because of:
As you know, the == operator, applied to wrapper objects, only tests whether the objects have identical memory locations. The following comparison would therefore probably fail:
Integer a = 1000;
Integer b = 1000;
if (a == b) . . .
However, a Java implementation may, if it chooses, wrap commonly occurring values into identical objects, and thus the comparison might succeed. This ambiguity is not what you want. The remedy is to call the equals method when comparing wrapper objects.