Java Equality not Behaving as Expected - java

I'm currently working on an android application that uses a subclass of SimpleListAdapter to bind a ListActivity. The list that the Adapter binds to is of type List<HashMap<String, Object>>.
I have to following If statement in the list Adapter...
if (dataRow.get("HasLineup1").toString()) == "0")
This never evaluates to true for me, even when the Eclipse debugger says that dataRow.get("HasLineup1").toString() is equal to "0" in the inspection window.
The list of data is populated from an XML source with the line
Game.put("HasLineup1", attributes.getNamedItem("home_lineup").getNodeValue());
I managed to work around the issue by changing the If statement to
if (Integer.parseInt(dataRow.get("HasLineup1").toString()) == 0)
Can someone explain to me why the first If statement I used wasn't working? Java isn't my native language, but I can't for the life of me figure out what I'm doing wrong based on my .Net background.

The == operator compares the instance memory location for non-primitive types therefore this fails unless the two sides of the operand are the same instance. Whenever dealing with non-primitive types, use equals instead of ==.

If you're using string you should do it with equals method.
if (dataRow.get("HasLineup1").toString())equals("0"))

The equality operator == will do the following, based on what you're comparing:
Two primitive types (e.g. int, char, ...): check if their values are the same.
Two non-primitive types (class instances): check if the compared references point to the same object in memory.
In other words, for non-primitives == doesn't imply semantics. You'll want the equals method for that. It's defined on Object so it'll always be available. But its semantics are determine by how (and if) a specific class decides to override this method.
For String, it's a character-by-character comparison with the argument of the method.

Here is a link with references about the differences between == and equals. == compares references, while equals() compares the values.
http://leepoint.net/notes-java/data/expressions/22compareobjects.html

Use
if (dataRow.get("HasLineup1").toString()).equals("0"))
== (double equals) only compares the objects to see if they point to the same place in memory. the equals method actually compares the characters in the two strings to one another.

You must use method "equals" or call .internal() on both strings before using "==".

Related

(Java) Comparing values of two variables in if-statement but can't use `.equals()`

(Heads up, I've never written a proper program before so bear with me)
I'm trying to write an if-statement that compares the VALUES of the position fields of two instances (which literally returns the integer "position"). Problem is, they are private fields in different classes so I cannot access them directly. Instead, I made methods in each class which return the variable.
Now in my if-statement, this is the condition that is to be true/false:
if (enemy1.getPosition() = player.getGun1Position())
Now the problem is, if I use = the machine assumes I'm trying to assign a value to the position of enemy1 and I've been researching to find that == compares the memory location rather than the value of the two fields.
I have also read that
.equals()
can be used but I'm assuming it can't be used here because
enemy1.getPosition().equals(player.getGun1Position())
gives an error when I try it.
NOTE: I cannot change the fields to public because this is for an assignment and the fields need to be private.
Any help would be appreciated :)
I'll briefly walk you through comparisons.
1) Primitives just need == operator to match values except, String values which are not permitives will compare their memory locations. for strings use .equals().
2) For objects of primitives like Integer,Double still compares the memory location with == operator. You need to invoke their .equals to compare them. If you have your own class you need to define your own version of equals method, means overriding.
Have you tried == yet?
If it is truly retiring a integer, than == is the way to go.
You can not call functions on primitives like int, char, double, float, long,short,byte. So there is no .equals() to call.
In the case of classes, you need to call .equals(), because a class variable is like a pointer, so you don't want to compare two pointers to each other with ==. However, primitive variables just contain their "values", so == is perfect for comparing values.
If you haven't tried this, you need to be more experimental with your coding.
Just test it.
System.out.println(enemy1.getPosition()+" == "+ player.getGun1Position()+": "+(enemy1.getPosition()==player.getGun1Position()));
if(enemy1.getPosition()==player.getGun1Position())
{
//blah
}
If that doesn't work, then you are not returning an int primitive, but instead an Integer object (note the capital I).
In this case,
if(enemy1.getPosition().equals(player.getGun1Position()))
OR
if(enemy1.getPosition().getIntValue()==player.getGun1Position().getIntValue()))
Should work fine.

How do I check in Java whether two references are holding the same object? [duplicate]

This question already has answers here:
Comparing references in Java
(5 answers)
Closed 7 years ago.
I am looking for a Java equivalent of pointer-comparison in C/C++.
Suppose I am invoking a getSomething() method of an object of a class from a third-party. How do I know if the implementation of the getSomething() is just returning the same instance everytime or returning a different instance of the object?
I am not looking to check whether two objects are identical, but need to check if they are the same instance or not. The motivation is, if the 3rd party implementation is creating a new instance everytime, probably I can optimize my code by not invoking the method everytime. Assume getSomething() is invoked by me 1000s of times a second at run-time
From what I read from various articles, I shouldn't rely on hashCode(). In that case what is the way to do this?
Reference types are "pointing to" the same object, when they are equivalent according to the == (identity) operator.
The question says:
I am not looking to check whether two objects are identical, but need to check if they are the same instance or not (emphasis mine)
You actually mixed equality with identity (as I did initially in the answer). Being the same instance is identity. Being the same value is equality.
The == operator compares the values held by the two operands. If the operands are primitive, the actual values are checked for equality. If the operands are of object type, then == checks for equality of identity, functioning in this role just like Python's is keyword.
Note that there is bit of fudginess caused by autboxing and autounboxing between primitive and wrapper object types.
== double equal operator are use to check whether two reference variable hold the same object or not.
Eg.
String s1 = new String("hello");
String s2 = s1;
String s3 = new String("hello");
System.out.println(s1==s2); // it prints true
System.out.println(s1==s3); // it prints false
s1 and s2 pointing to the same object.
s3 holds newly created object and hence s1 == s3 prints false
I think you're not looking for the ==operator. To compare two instances of an object, for example, I use the equals() Object method. Here are two useful links about comparisons:
java ==, equals(), compare(), compareTo()
Javadocs equals() method
You can use == operator to compare two objects if they are having same reference or not.

Comparing 2 Points - java

I've noticed that you can't compare 2 points like this:
if (pointOne == pointTwo) { }
I always have to do it like this:
if (pointOne.x == pointTwo.x && pointOne.y == pointTwo.y) { }
I really wonder why you can not use the first example, does anyone have an answer?
You must use the equals method of class Point. Check this.
If you use == what you are actually doing is checking if the memory address of the two Point objects is the same.
In Java, all classes are derived from Object, and you can override the equals method, providing a convenient way of checking if in fact, two objects of the same Object derived class, are the same.
== operator checks both reference pointing to the same object or not.
You should use equals method of Point object -
pointOne.equals(pointTwo);
Determines whether or not two points are equal. Two instances of
Point2D are equal if the values of their x and y member fields,
representing their position in the coordinate space, are the same.
Documentation
Because the Point is reference, and if you need to use equals, you need to override the method equal. Java doest not support override operators like "==".
I assume pointOne and pointTwo are objects of some class? You cannot overload operators in java, that is why you have to compare fields.
In such cases it is a good practive to override the equals method for your class and use it this way:
PointOne.equals(PointTwo)
Well this will be an object comparison. You would be comparing memory locations if you compare using ==.
You could override and call Equals.
You can use your first example because running pointOne.x == pointTwo.x compares the primitive types (int) which the == operator is capable of.
When you run pointOne == pointTwo you're comparing the Point object references, which they're not.
As others have said, you can use pointOne.equals(pointTwo)

in which cases equals() is similar to ==? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Difference Between Equals and ==
in which cases equals() works exactly like == operator?
It seems that they both act similar for primitive data types. Are there any other cases in which both of them act equal?
== compares the bits of reference for Object type so if you have reference to same Object it would be the case
For example
Integer for value -128 and 127 (inclusive) it caches (while autoboxing) the instance so it would be the case here for the mentioned range of value of Integer
For primitive data types, there is no equals() (because they are not objects, and have no methods).
The default implementation (in class Object) for equals() just does object identity check (i.e. the same as ==). So if a class does not override it, it will have the same result as ==.
The operator == will always compare references for objects, and the actual value for primitive types.
Note that an array of primitives like int[] is still an object!
String test1 ="test";
String test2 = test1;
System.out.println(test1 == test2);
System.out.println(test1.equals(test2));
Both will print -
true
true
In addition to primitives (which are a special case) == and equals() behave similarly for every case in which reference equality is the same as actual equality:
Interned Strings
Certain Integer references (normally between -128 and +127, but this is configurable, and it depends on how the instance was constructed)
Singletons
Instances of Object (and any other class that doesn't override equals())
Obviously, when in doubt, use equals()
The equals() method evaluates on hashCode comparisons. While == compares objects by reference.

Difference between the two Java operators: != vs !equals

Is this code:
elem1!=elem2
equivalent to this one?
!elem1.equals(elem2)
It compiles both ways, but I'm still unsure about it...
== (and by extension !=) check for object identity, that is, if both of the objects refer to the very same instance. equals checks for a higher level concept of identity, usually whether the "values" of the objects are equal. What this means is up to whoever implemented equals on that particular object. Therefore they are not the same thing.
A common example where these two are not the same thing are strings, where two different instances might have the same content (the same string of characters), in which case a == comparison is false but equals returns true.
The default implementation of equals (on Object) uses == inside, so the results will be same for objects that do not override equals (excluding nulls, of course)
In general, no they're not the same. The first version checks whether elem1 and elem2 are references to the same object (assuming that they're not primitive types). The second version calls a type-specific method to check whether two (possibly distinct) ojects are "equal", in some sense (often, this is just a check that all their member fields are identical).
I don't think this has anything to do with generics, as such.

Categories

Resources