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)
Related
(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.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Equals method for objects
i have below code.
public class SomeClass{
OtherClass clas = new OtherClass();
OtherClass some;
some=this;
if(some != this) {
s.y.s.o("true");
}
my question is which one is correct?
some != this or some.equals(this) ?
To compare object references, you use == and !=, while equals is used to compare the values.
What do you want to compare?
== compares to see if the two references are to the EXACT SAME OBJECT.
equals compares to see if the two references are to objects which have matching properties, based on the class-specific criteria in the class's equals implementation.
You use operator!= or operator== when you want to check for identity of two objects [if they are actually the same object]
You use equals() when you want to check for equality. [if two object are equal, as the equals() method defined them].
It is hard to know what exactly you are trying to achieve, but usually when comparing two reference objects, we want to use equals().
In Java == compares references (i.e. addresses) while equals compares object equality (and you can override it to compare based the member variables you see fit)
In your post you compare to see if some is the same object as this. Is this what you want to do? If yes then the some!=this is correct (and is false since some refers to this)
== compares the references. That is, are these two objects located at the same place.
.Equals compares the things pointed to by those references. That is, are these two objects equivalent.
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 "==".
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.
I have the following situation: I need to sort trees based by height, so I made the Tree's comparable using the height attribute. However, I was also told to overwrite the equals and hashCode methods to avoid unpredictable behaviour.
Still, sometimes I may want to compare the references of the roots or something along those lines using ==. Is that still possible or does the == comparison call the equals method?
equals() is meant to compare an object with rules set by the programmer. In your example you compare your trees by height, so you'll write equals() so it compares heights.
==, as you said, compares references. These aren't touched neither by equals() nor by hashCode(). So you won't change its behaviour.
Yes, == will not call hashCode or equals. You can still test for reference equality like this.
== does not call equals. So it's still find for identity checks.
As many implementations of equals start with this == other check you would get a literal StackOverflow if it were calling equals behind the scenes.
I think that a bigger question here is whether it is appropriate to implement comparable on these objects. It may be more appropriate to use a Comparator for the operations that work on height, and not embed ordinal computation in the class itself.
My general philosophy on this is to only implement Comparable if there is a truly natural ordering for the object. In the case of a tree node, is height the only way that anyone could ever want to sort? Maybe this is a private class, and the answer is 'yes'. But even then, creating a Comparator isn't that much extra work, and it leaves things flexible in case you decide you want to make that tree node a protected or public class some day.
== tests referential equality. It will not call equals.
Overriding the equals() method will have NO effect on the == operator.
== is used to test if 2 references point to the same object.
equals() method "meaningfully" compares 2 objects.
It is important to realize the implication of the work "meaningful" here. Equality is easier to understand when you are comparing, for instance, 2 Strings or 2 integers. This is why, the equals() method - inherited from the Object class - is already overridden by the String and Wrapper classes (Integer, Float, etc). However, what if you are comparing 2 objects of type Song. Here, equality can be established on the basis of
1) Artist name
2) Song name
3) or some other criterion
Therefore, you have to override the equals() method to "explicitly" determine "when" 2 Song objects are considered equal.
The "unpredictable behavior" you mentioned in your question relates to objects like the one above (Song) behave when dealing with Collections like Map. You SHOULD NOT use these objects in a map until you override both the equals() and hashcode() method. The reason being how hashmap search and indexing works. Refer the JavaDoc for the specifc rules. What you should remember is:
If 2 objects are meaningfully equal, their hashcode should return the same value. However, it is not necessary for 2 objects to be equal, if they return the same hashcode. Again, Java doesn't enforce any rules regarding this. It is your responsibility to implement the equals() and hashcode() methods correctly.