今天我遇到了一些代码,我觉得有些问题。这是一个简化的例子(不真实)。
public interface IListable {
//returns first n items from list
public ArrayList getFirstNThings(int n);
//returns last n items from list
public ArrayList getLastNThings(int n);
}
然后有一个实现者,如下所示:
public GroceryList implements IListable {
private ArrayList<GroceryItem> groceries;
public GroceryList() {
this.groceries = new ArrayList<GroceryItem>();
}
public ArrayList<GroceryItem> getFirstNThings(int n) {
ArrayList<GroceryItem> firstNThings = new ArrayList<GroceryItem>();
for (int i=0; i < n; i++) {
firstNThings.add(this.groceries.get(i));
}
return firstNThings
}
public ArrayList<GroceryItem> getLastNThings(int n) {
ArrayList<GroceryItem> lastNThings = new ArrayList<GroceryItem>();
for (int i=this.groceries.size(); i < this.groceries.size()-n; i--) {
lastNThings.add(this.groceries.get(i-1);
}
return lastNThings;
}
}
忽略你可能在其中发现的任何实现问题(我也发现了一些)。我的意思是该接口没有使用任何ArrayList的通用类型参数(即ArrayList<?>),但是接口方法的实现者却使用了(即ArrayList<GroceryList>)。其他实现者可能会返回具有任何其他类型参数的ArrayList,对吧?
那么我的问题是:这是一个问题吗?我应该重构任何东西吗?这值得吗?有什么优点?如果我在接口中定义了一个返回类型为原始类型的方法,但实际的实现者返回了各种参数化类型,我可能会遇到什么问题?
List
而不是ArrayList
。 - Michael Myers