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

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.

Related

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.

About Java memory management [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Integer wrapper objects share the same instances only within the value 127?
I have a question about the memory management in Java.
When I try the following code:
Integer a = 1;
Integer b = 1;
System.out.println(a==b); // this gives "true"
However,
Integer a = 256;
Integer b = 256;
System.out.println(a==b); //this gives "false"
Why?
Thanks very much.
That is because "autoboxing" uses Integer.valueOf, and Integer.valueOf keeps a cache of Integer objects for small integer values. Here's what the JLS says:
"If the value p being boxed is true, false, a byte, or a char in the range \u0000 to \u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2." JLS 5.1.7.
When you use the == operator to compare a pair of Integer objects, it is actually comparing the object references. So your get true if boxing gave you the same cached Integer object, and false if it didn't. Note that the JLS guarantees this behaviour for the ranges stated, but it also permits an implementation of the valueOf method to cache a wider range of values.
The bottom line is that you should use equals(Object) to compare Integer objects ... unless you are really trying to test if they are the same object.
According to what I read, "Integer" should create an "object" in the heap, thus the two objects should be the same.
If your code explicitly does a new Integer(...), it is guaranteed to create a new Integer object. However, autoboxing uses Integer.valueOf(...), and that is where the caching behaviour is implemented.
You shouldn't use reference equality (==) for objects. It's printing true in your first example because the first 128 Integer objects are cached by the Integer class. Use .equals()
When the values greater than range of data representation, they are different object because they are wrapped. You are now coparing like object ids.
You are comparing objects' addresses

how to compare two objects/references in java? [duplicate]

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.

Java Equality not Behaving as Expected

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 "==".

== operator for primitive data types [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How Does the toString(), ==, equals() object methods work differently or similarly on reference and primitive types?
I am trying to understand the difference between == and equals to operator in Java.
e.g. == will check if it is the same object while equals will compare the value of the object ... Then why do we use == for comparing primitive data types like int.
Because if I have
int i =7; //and
int j = 6.
They are not the same object and not the same memory address in stack. Or does the == behaves differently for primitives comparison.??
Actually, == behaves identically for all variables: it tests whether the values of those variables are equal. In the case of Object obj, obj is a reference to an object. Since == tests whether two object references have the same value, it is testing whether they refer to the identical object (i.e., that the references are equal).
== intuitively work differently on primitive types. Its just that way in the language.
If you think about it in C++ terms, references are pointers and == does pointer comparison.
int* myPtr1 = new int(5);
int* myPtr2 = new int(6);
myPtr1 == myPtr2;

Categories

Resources