我一直在寻找比较器的这段代码。我的问题是在构造函数中初始化两个私有(private)变量有一个特定的好处(在默认构造函数中完成)。我知道第二个构造函数可用于创建具有提供值的实例。如果我这样做会有什么不同
private String sortBy = COLUMN_LAST_NAME;
private boolean ascending = true;
如果这是一个真正简单而笼统的问题,我深表歉意。
public class CustomComparator implements Comparator<StudentList>
{ private String sortBy;
private boolean ascending;
public CustomComparator()
{
sortBy = COLUMN_LAST_NAME;
ascending = true;
}
public CustomComparator(String sortBy, boolean ascending)
{
this.sortBy = sortBy;
this.ascending = ascending;
}
最佳答案
我见过到处宣扬的最佳实践是拥有一个接受所有参数的构造函数,即使这意味着它必须是私有(private)的,然后使用 this(..,.. ,...)
同时提供适当的值。
这将使您重用尽可能多的代码,并且将来的修复只会去一个地方和一个地方 - 无需对代码进行双重维护。
你的例子看起来像这样:
public class CustomComparator implements Comparator<StudentList> {
private String sortBy;
private boolean ascending;
public CustomComparator()
{
this(COLUMN_LAST_NAME, true);
}
public CustomComparator(String sortBy, boolean ascending)
{
this.sortBy = sortBy;
this.ascending = ascending;
}
}
初始化通常被接受在构造函数中,以便更容易区分静态成员的静态初始化和实例变量的每个实例初始化。没有性能差异。
关于java - 在构造函数中初始化私有(private)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5071178/