0

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;
  }

}
4

1 回答 1

1

您的代码中有一些错误。导致您的问题的直接原因是您的构造函数正在隐藏实例变量,因此它们在构造时永远不会改变,就像您在测试类的 toString 方法时所看到的那样。

public Author(String ln, String fn) {
    String lastName = ln; //Remove 'String'
    String firstName = fn; //Remove 'String'
}

秉承我的风格,我会这样编写构造函数:

public Author(String lastName, String firstName) {
    this.firstName = firstName; //Using the 'this' makes it clear to me exactly what I wish to happen...
    this.lastName = lastName;
}

'阴影是一个更高范围的变量被阻塞的地方,因为它与一个更接近的范围内的变量共享它的名称(实际上通常是一个参数,但它可能是一个在那里声明的参数)。因为它们都共享相同的名称,所以使用范围最接近的名称来减少歧义,您可以使用this关键字来访问实例范围,或使用 ClassName 来访问静态变量。要记住的主要事情是,在声明变量时,编译器不一定会告诉你你已经隐藏了一个变量,因为它可能是故意的,所以如果你重用名称,请确保你在你希望的范围内访问那个. 也许这里有更多帮助......

于 2013-11-06T01:21:32.967 回答