我试图让我的代码使用泛型,但我似乎无法使用泛型让它工作。任何帮助,将不胜感激。我有 3 个班级:课堂、课程、教师我有以下工作代码 3 次:(随着班级的小变化)private ObservableList<Classroom> parseClassrooms() { // create new Observable List ObservableList<Classroom> classrooms = FXCollections.observableArrayList(); // get lines from file; ArrayList<String> arrayList = fhClassroom.read(); for (String line : arrayList) { classrooms.add(Classroom.fromString(line)); } return classrooms;}我的课程中的方法:@Overridepublic String toString() { return name;}public static Classroom fromString(String line) { return new Classroom(line);}是否可以使这种方法通用?并将类作为参数传递?我想要以下内容:private ObservableList<T> parseClassrooms(T, FileHelper fh) { // create new Observable List ObservableList<T> items = FXCollections.observableArrayList(); // get lines from file; ArrayList<String> arrayList = fh.read(); for (String line : arrayList) { items.add(T.fromString(line)); } return items;}
1 回答
陪伴而非守候
TA贡献1757条经验 获得超8个赞
我最好的尝试:
import java.util.ArrayList;
import java.util.function.Function;
public class Helper {
public static <T> ObservableList<T> parseItems(Function<String, T> lineToItemFunction, FileHelper fh) {
// create new Observable List
ObservableList<T> items = FXCollections.observableArrayList();
// get lines from file;
ArrayList<String> arrayList = fh.read();
for (String line : arrayList) {
items.add(lineToItemFunction.apply(line));
}
return items;
}
}
你这样称呼它:
ObservableList<ClassRoom> classRooms = Helper.parseItems(ClassRoom::fromLine, fileHelper);
添加回答
举报
0/150
提交
取消