Making confrontable ClassesFrom WikiJavabuy this book
This article shows how to create a class whose instances are comparable. This means that when you have two objects from this class they can be compared and a
ExplanationWhen you write in Java a statement like this: if (var1 == var2) { //do something } The
There's a very simple reason to this, and it depends on how Java refers to objects internally. see now the following example: String var1 = new String ("a"); String var2 = new String ("a"); if (var1 == var2) { //this is never executed. } Why the code inside the If statement is never executed? because In general confrontable Objects will always implement the The example above can be corrected now in: String var1 = new String ("a"); String var2 = new String ("a"); if (var1.equals(var2)) { //this is always executed. } Note that now there's a call to the method NOTE: It is very simple to get confused and use How to implement the equals method in your classes and make them comparable? That's very simple. Let's see it in the example below, taken from the class Job: public boolean equals(Job job) { if (!this.contactEmail.equals(job.getContactEmail())) { return false; } if (!this.description.equals(job.getDescription())) { return false; } if (!this.title.equals(job.getTitle())) { return false; } return true; } As you can see this is a normal method, with signature:
Where the Type of the parameter must be the same as the class (the parameter must be The method just checks the various values (or it performs any algorithm) and returns true if the two objects are equal. That's it. easy no?
|
