I'm writing a class method to compare two author objects fields.
public int compareTo(Author b) {
int i = -2;
String afn = this.firstName;
String aln = this.lastName;
String bfn = b.firstName;
String bln = b.lastName;
if(afn.equals(bfn)) { i++; }
if(aln.equals(bln)) { i++; }
return i;
}
However when I pass through an author object with different strings it still returns zero. Is there something wrong with my approach? Also is "this" necessary for the method?
Here's the class.
public class Author {
String firstName = TITLE_NOT_SET;
String lastName = TITLE_NOT_SET;
int birth = YEAR_NOT_SET;
int death = YEAR_NOT_SET;
public Author(String ln, String fn) {
String lastName = ln;
String firstName = fn;
}
public int getDeath() {
return death;
}
public int getBirth() {
return birth;
}
public void setDates(int b) {
if(b > 2018 || b < -2000) { b = birth; }
birth = b;
}
public void setDates(int b, int d) {
if(b > 2018 || b < -2000) { b = birth; }
if(d < b) { d = death; }
birth = b;
death = d;
}
public int compareTo(Author b) {
int i = -2;
String afn = this.firstName;
String aln = this.lastName;
String bfn = b.firstName;
String bln = b.lastName;
if(afn.equals(bfn)) { i++; }
if(aln.equals(bln)) { i++; }
return i;
}
public String toString() {
return lastName + ", " + firstName;
}
}