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
Related
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);
This question already has answers here:
Comparing Integer objects vs int
(5 answers)
Closed 6 years ago.
While writing a graph algorithm, I saw that this -
Definition:
Map<Integer, Integer> componentNames = new HashMap<Integer, Integer>();
CASE I:
if (componentNames.get(A) == componentNames.get(B)) {
System.out.printn("Hi");
}
Does not print anything.
CASE II:
int componentNameA = componentNames.get(A);
int componentNameB = componentNames.get(B);
if (componentNameA == componentNameB) {
System.out.printn("Hi");
}
Prints "Hi"
I have printed to check the values. And, they were indeed same.
This is the first time I have seen strange behavior for Java.
What could be the reason for this?
CASE I:
if (componentNames.get(A) == componentNames.get(B)) {
System.out.printn("Hi");
}
The code doesn't enter the if condition because you are trying to compare two Integer references using == which will only return true if the LHS and RHS refer to the same object. In your case, it is safe to assume that componentNames.get(A) and componentNames.get(B) both return a reference to a separate Integer object.
It would be helpful to know that the JVM caches the values for wrapper classes and it is quite possible that the above if condition may be true if the JVM has cached the int value returned by componentNames.get(A) and componentNames.get(B). The JVM used to cache Integer values ranging between -128 to 127 but modern JVMs can cache values greater than this range as well.
int componentNameA = componentNames.get(A);
int componentNameB = componentNames.get(B);
if (componentNameA == componentNameB) {
System.out.printn("Hi");
}
The code enters condition because you are unboxing an Integer into an int and the comparison is done between two primitive values.
In general, two references when compared using == will only return true if both the references point to the same object. Therefore, it is advisable to compare two references using equals if you are checking for equality and compare them using == if you are looking to check for identity.
CASE 1:
componentNames.get(A) and componentNames.get(B) are references / pointers of two different instances of Integer Class.
So, componentNames.get(A) == componentNames.get(B) is false.
CASE 2:
int componentNameA and int componentNameB are int type variables.
As they both contain same value, componentNameA == componentNameB is true.
This question already has answers here:
How can I express that two values are not equal to eachother?
(4 answers)
Closed 8 years ago.
How is it possible to show if it's not equal (!=, something like this maybe) in an if statement?
For example:
for (int g = 0; g < doglist.size(); g++){
if(doglist.get(g).equals(name)){
System.out.println("There is no dog with that name: ");
}
}
So in this code I want to print the message if the entry in the list is not equal to name. So instead of equals(name) I'll have to use something different. How is this possible?
You can use the NOT operator ! with appropriate parentheses for clarity (though not strictly required).
if (!(condition))
so in your case....
if(!(doglist.get(g).equals(name)))
You should write
if (!doglist.get(g).equals(name))
About your idea of using !=: For primitive data types, yes, it's correct to test equality using !=. .equals() is for object data types. However, applying != to an object would be testing whether the memory location of the operands is the same, which is not the relevant information. .equals() is what tests for whether the objects are actually equal.
For example, when comparing ints (a primitive type), you would use !=:
int a = 0, b = 1;
if (a != b) doSomething(); //Calls the method
Primitive types do not recognize the .equals() method at all. But if you want to compare Strings (an object type), you would use !<object>.equals():
String s1 = "Hello", s2 = "World";
if (!s1.equals(s2)) doSomething(); //Calls the method
If you used != with an object, it would compile, but likely would not produce the desired output:
String s1 = "Hello!";
String s2 = "Hello!"; //Make a new object with the same data -- contains "Hello!"
if (s1 != s2) doSomething(); //Will run doSomething(), even though s1.equals(s2)
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Integer wrapper class and == operator - where is behavior specified?
I known Java integer use cache in -127~128.
If
Integer i = 1;
Integer j = 1;
Integer m = 128;
Integer n = 128;
i == j // true
m == n // false
But I met a strange phenomenon.First,look at following snippet.
List<CustomerNotice> customerNotice = findByExample(example); // use Hibernate findByExample method
for(CustomerNotice n : customerNotice){
if(n.getConfirmStatus() == NoticeConfirmStatus.UNCONFIRMED.getValue()){
// do sth
}
}
public enum NoticeConfirmStatus{
UNCONFIRMED(1), //
CONFIRMED(2), //
FAILED_TO_CONFIRM(3); //
private final Integer value;
private NoticeConfirmStatus(Integer value) {
this.value = value;
}
public Integer getValue() {
return this.value;
}
}
public class CustomerNotice {
#Column(name = "CONFIRM_STATUS")
private Integer confirmStatus;
public Integer getConfirmStatus() {
return this.confirmStatus;
}
public void setConfirmStatus(Integer confirmStatus) {
this.confirmStatus = confirmStatus;
}
}
Although the if expression is not recommended, I think it will be return true,because n.getConfirmStatus()==1, but the result is false.I'm very confusing.
In addition, theList<CustomerNotice> customerNotice acquired by Hibernate findByExample method. Is there some Autoboxing or new operation when retrieve the resultset?
Thank you.
SHORT: (answers question)
If you want to compare Integers as the objects, you should use .equals:
i.equals(j);
m.equals(n);
With this, they should both return true. But if you really want to use ==, you need to get the primitive int value:
i.intValue() == j.intValue();
m.intValue() == j.intValue();
LONG: (explains answer)
The basis of this is that Objects are always stored separately in memory (except for some special cases like m=n), and to be compared properly, they need to be broken down into primitive types that can be compared successfully using ==.
Every Object has a .equals() method, which is inherited from Object as its superclass. However, it must be overridden to do a proper comparison. Integer overrides this method to compare to Integer objects successfully, while using == checks to see if both objects point to the same space in memory, and because two instances of an Object cannot point to the same space in memory, this will always return false.
However, as your code points out, there are some special cases that work, like these:
Your code uses a Integer i = 1, which is considered a "standard instance" and is able to be compared using ==.
If you set one Object equal to another using =, Java tells both objects to point to the same location in memory, which means that == will return true.
There are many others, but those are the two that come to mind and seem relevant.
You'll drive yourself crazy and waste a lot of time trying to figure out specific cases where this works or does not work. It depends on the implementation of code which isn't always visible to you.
The bottom line: never, ever, use == to compare Integer instances, period. As you have seen, it works sometimes, under some circumstances, and fails miserably the rest of the time. If you have a method that returns an Integer, then assign the value to an int, and then you can use == to compare that int to another int.
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.