I expecting the following to return true.
public class HudsonJob {
private String name;
private String status;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public boolean equals(Object jobName) {
return name.toLowerCase().equals(((String)jobName).toLowerCase());
}
public int hashCode() {
return name.hashCode();
}
}
,
List<HudsonJob> existingJbsLst = hudsonUtil.getAllJobs(); // returns multiple HudsonJob objects in the list.
The statement I’m expecting to return true is :
boolean isExistingJob = existingJbsLst.contains("AnExistingJOB");
is always returning false.
OR
boolean isExistingJob = existingJbsLst.equals("AnExistingJOB"); is also returning false.
What should I add/change in the code to get the expected return value.
The “contains” operator loops through all the memers of the set, and compares the “want” value to the “found” value. I say that very carefully. If you say “joblist.contains(wantjob)”, this gives — to leave out some complexity, the relevant part:
That is, the comparison is “objectIAmLookingFor.equals(objectInList)”, NOT “objectInList.equals(objectIAmLookingFor)”.
So when you search a list of HudsonJob’s for a String, it is using the String.equals function, NOT your HudsonJob.equals function. And String.equals knows nothing about HudsonJobs, so it promptly returns false.
There are two ways to do what you want.
One way is to change your HudsonJob.equals function to
Then write
The other way is to not use “contains” but instead write your own search function, like:
(Actually if you need the toLowerCase it would be better to do the wantJob.toLowerCase before the loop, but whatever.)
Then you can say