This question already has answers here:
Comparing integer Arrays in Java. Why does not == work?
(3 answers)
Closed 6 years ago.
When I am trying to compare two int array, even though they are exactly the same, the code inside if (one == two) still doesn't get executed. Why is this?
Object[] one = {1,2,3,4,5,6,7,8,9};
Object[] two = {1,2,3,4,5,6,7,8,9};
if (one == two){
System.out.println("equal");
} else {
System.out.println("not equal");
}
A few things to note here:
== compares the references, not the values . . . that is, you are asking whether these two arrays are the same exact instance, not whether they contain the same values.
The fact that you are using == means you may not know about the equals() method on Object. This is not the method you'll need to solve this current problem, but just be aware that in general, when you compare the values of two objects, you should be using obj1.equals(obj2), not obj1 == obj2. Now == does work with primitives like int (e.g. plain old x == 3 and so on), so maybe that's why you were using it, but I just wanted to make sure you were aware of equals() vs. ==.
In the old old days (pre-1998), you would have to compare each element pair of the two arrays. Nowadays, you can just use that static Arrays.equals() method on the java.util.Arrays class. This method is overloaded for all the primitive types (using == under the hood for each element pair) and for Object (where it will most definitely use equals() for each pair.)
The == operator does a reference equality check on objects (which arrays are). If the array elements are primitive (like int), you can use java.util.Arrays.equals. If they are themselves Objects, java.util.Arrays.deepEquals will do a deep equality test (provided the Objects in the array supply a suitable override of Object#equals.
You can do something like that:
public boolean compareArrays(int[] a, int[] b) {
boolean check = true;
if (a!= null && b!= null){
if (a.length != b.length){
check= false;
}else
for (int i = 0; i < b.length; i++) {
if (b[i] != a[i]) {
check= false;
}
}
}else{
check= false;
}
return check;
}
Or you could do something like that:
boolean areEqual = Arrays.equals(Arrays.sort(arr1), Arrays.sort(arr2));
You are comparing references. Compare the content instead with: Arrays.equals(one, two)
If you do this:
if (one == two){
then yo are comparing the references of the 2 arrays and not their content and that is wrong..
do instead
Arrays.equals(one, two)
== operator compares references and not actual values of everything that extends Object in java. This approach works on primitives only.
Related
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:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm in little trouble. The problem is when I'm trying to compare 2 strings(type String) operator '==' returns FALSE, but actually strings are equal.
Here's the code with its problem:
//before the following code I filled the "LinkedList <String> command" and there is
//a node with value of args[0]
String deal="";
Iterator it = commands.listIterator();
if(it.hasNext() == true)
{
if(it.next() == args[0])
{
deal += it.next();
it.hasNext();
break;
}
}
Thank You!!!
To compare two strings u should use the method equals() or equalsIgnoreCase().
in your case:
if(it.next().equals(args[0]))
the operator == returns true if the two object are the same object, same address in memory.
You use .equals when comparing two strings. So use
(it.next()).equals(args[0])
You have to use .equals method:
String deal="";
Iterator it = commands.listIterator();
if(it.hasNext() == true)
{
String next = it.next();
if(next.equals(args[0]))
{
deal += next;
break;
}
}
Be careful, .next() returns the value once and move its internal cursor to the next value.
The == cannot be used for String because the == is true if the same object instance is on both sides. The same string content can be in many String instances.
There are two ways of comparing strings.
Comparing the value of the strings (achieved using .equals ).
Comparing the actual object (achieved using == operator).
In your code you are comparing the references referred by it.next() & args[0]whereas you should compare the value of the two using it.next().equals(args[0]).
if you use == to compare two int values, then it is compare the two values, because int is primitive data type. If you use "==" to compare String object, it is check whether both String reference are referring the same String object or not. It do not consider values of the String objects.
If you want to compare values of String objects you have to use equals() of the String class. This method is comparing content of both String objects.
I have two different objects of same entity “Community”
And two objects(community and com) have same values
Communty.java have following variables:
private Integer communityId;
private String communityName;
private String description;
// many to many relationship
private Set<Faculty> faculties = new HashSet<Faculty>();
private Set<User> users = new HashSet<User>();
and I used equal method as:
#Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
if(obj==null)
return false;
if(obj==this)
return true;
if(!(obj instanceof Community)) return false;
Community community = (Community)obj;
return community.getCommunityId() == this.getCommunityId();
}
When I checked community==com , it returns false .. why? What mistake I have done? Both the objects are retrieved from the database!
== compares links to the objects.
You should explicitly call community.equals(com). Also take care of the null checks.
Because you're comparing objects (the IDs) using == rather than equals(). == tests if both variables reference the same object. equals() tests if the two variables reference two functionally equal integers (i.e. with the same int value).
It's almost always a bug to compare objects using ==, except for enums.
== compares the two references which may be pointing to two different locations irrespective of the object content.
You should use community.equals(com) to check for equality'
Also, your equals method contains the following segment :
community.getCommunityId() == this.getCommunityId()
as communityId is an Integer object, the == operator may give negative result for integer values which are not in the range [-127, 128] due to interning, thats a separate concept, you can check it later.
You need to use equals() there as well or compare the .intValue()
return community.getCommunityId().equals(this.getCommunityId())
Because, they don't refer same object. == used to check, whether both referring same object.
== for object refer to same.
equals content equivalency.
try this
return community.getCommunityId().equals(this.getCommunityId());
The problem of your equals method is that you are using == operator for Objects. And here the CommunityId must be the same object in order to return true:
return community.getCommunityId() == this.getCommunityId();
It should be
return community.getCommunityId().equals(this.getCommunityId());
When I checked community==com , it returns false .. why
This means; are these two references exactly the same. i.e. to the same object. What you intended was
boolean equal = community.equals(com);
BTW Your if (obj == null) check is redundant.
== operator in Java compares the memory address of the two objects,in your case comm and community must be two different objects stored at two different memory addresses
You are comparing two distinct objects communityId's.
is it necessary to declare communityId as Integer? because Integer is an object.
Why don't you simply declare communityId with a primitive type int;
int communityId should work.
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.