我遇到了重复代码的问题,不知道应该如何解决。 我有2种几乎相似的方法,以后我知道还会有更多方法。
public static List<ExamResult> numberOfMarks(List<ExamResult> allMarks, int offset, int records) throws DaoException {
List<ExamResult> result = new ArrayList<>();
for (int i = 0; i < allMarks.size(); i++) {
if (offset == 0) {
if (i < records) {
result.add(allMarks.get(i));
}
} else if (offset > 0) {
if (i > offset * records && i < (offset * records + records + 1)) {
result.add(allMarks.get(i));
}
}
}
return result;
}
public static List<Question> numberOfQuestions(List<Question> allQuestion, int offset, int records) throws DaoException {
List<Question> result = new ArrayList<>();
for (int i = 0; i < allQuestion.size(); i++) {
if (offset == 0) {
if (i < records) {
result.add(allQuestion.get(i));
}
} else if (offset > 0) {
if (i > offset * records && i < (offset * records + records + 1)) {
result.add(allQuestion.get(i));
}
}
}
return result;
}
答案 0 :(得分:4)
您可以使用“ generic methods”。该方法将是:
public static <T> List<T> extract(List<T> input, int offset, int record) {
... //the same code with T instead of Question or Answer
}
答案 1 :(得分:1)
“泛型”就是答案。以下是一种可行的方法。
public <T> List<T> numberOfQuestions(List<T> allItems, int offset, int records) {
List<T> result = new ArrayList<>();
for (int i = 0; i < allItems.size(); i++) {
if (offset == 0) {
if (i < records) {
result.add(allItems.get(i));
}
} else if (offset > 0) {
if (i > offset * records && i < (offset * records + records + 1)) {
result.add(allItems.get(i));
}
}
}
return result;
}
答案 2 :(得分:0)
我们可以使用方法List#subList(int fromIndex, int toIndex)
来实现您想要的:
public static <T> List<T> getEntries(
List<T> list,
final int offset,
final int records) {
final int listSize = list.size();
final int fromIndex;
if (offset == 0) {
fromIndex = 0;
} else if (offset * records + 1 < listSize) {
fromIndex = offset * records + 1;
} else {
fromIndex = -1;
}
final int toIndex;
if (offset + records <= listSize) {
toIndex = offset + records;
} else {
toIndex = listSize;
}
final List<T> result;
if (fromIndex >= 0) {
result = list.subList(fromIndex, toIndex);
} else {
result = Collections.emptyList(); // or new ArrayList<T>() if you want to modify the list
}
return result;
}
public static List<ExamResult> numberOfMarks(
List<ExamResult> allMarks,
final int offset,
final int records) throws DaoException {
return getEntries(allMarks, offset, records);
}
public static List<Question> numberOfQuestions(
List<Question> allQuestions,
final int offset,
final int records) throws DaoException {
return getEntries(allQuestions, offset, records);
}