dirdir69
dirdir69

Reputation: 47

Logical Operators exhibiting strange behavior

if ((File_1[i].ID.equals(File_2[j].ID)) 
&& (File_1[i].Relation.equals(File_2[j].Relation)))

The first condition here, (File_1[i].ID.equals(File_2[j].ID) shows false when it is supposed to be true. They both have equal values.

Am I doing something wrong? This is unusual.

ID: fa001
ID: fa001

These are the values of the first 2 variables that are compared, but it shows up as false.

Upvotes: 2

Views: 92

Answers (2)

La-comadreja
La-comadreja

Reputation: 5755

The original poster has said the ID is a String type and there are whitespaces around the String. In order to remove the whitespaces of String s:

s = s.trim();

However, if ID is a type you have created, make sure you implement the .hashCode() method. From the Javadocs:

If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

Also make sure that .equals() is overridden from class Object to allow for your definition of whether the values of your new object type are equal.

Upvotes: 3

Adam Yost
Adam Yost

Reputation: 3625

Depending on the TYPE of ID (int, string, char[], etc) the .equals method can do some weird things. Assuming they are strings, try comparing ID.trim(), which will remove any witespace around the ID.

Upvotes: 1

Related Questions