java - 返回对对象列表的引用
问题描述
我创建了两个类:DVD 类和 ListOfDVDs 类。我的类 ListOfDVDs 中有一个方法可以将新 DVD 添加到列表中(这只是一个 DVD 数组)。但是,现在我应该创建一个方法,该方法将读取包含多张 DVD 的文本文件,将它们全部添加到 ListOfDVDs 并返回对新创建的 ListOfDVDs 对象的引用,该对象包含来自文本文件的所有 DVD。但是,我不确定如何创建一个新对象并从我的方法内部调用它的方法。我必须创建一个新的 ListOfDVDs,将文件中的 DVD 添加到其中,然后将其返回。不知道该怎么做。我已经有一种方法可以将 DVD 添加到列表中:它是 listOfDVDs.add。谢谢
到目前为止,我的代码如下所示:
public class listOfDVDs {
private DVD[] DVDs;
public listofDVDs() {
DVDs = new DVD[0];
}
public void add(DVD newDVD) {
if (newDVD == null) {
return;
}
DVD[] newDVDs = Arrays.copyOf(DVDs, DVDs.length + 1);
newDVDs[newDVDs.length - 1] = newDVD;
DVDs = newDVDs;
}
public static listOfDVDs fromFile(String filename) {
Scanner sc = null;
String name = null;
int year = 0;
String director = null;
try {
sc = new Scanner(new File(filename));
while (sc.hasNext()) {
name = sc.next();
year = sc.nextInt();
director = sc.next();
}
} catch (FileNotFoundException e) {
System.err.println("file not found");
} finally {
if (sc != null) {
sc.close();
}
}
}
}
public class DVD {
private String name;
private int year;
private String director;
public DVD(String name, int year, String director) {
this.name=name;
this.year=year;
this.director=director;
}
}
解决方案
你需要一个名为 的类型ListOfDVDs
吗?你可能只想要一个java.util.List
. DVD
你可以这样写:
List<DVD> list = new ArrayList<DVD>();
如果你必须有一个 listOfDVDs 类型,你应该按照约定以大写字母开头它的名称:ListOfDVDs
. 但同样,这可能包含一个java.util.List
. 你说你想要一个数组。列表会更好,但让我们坚持你想要的。
鉴于您更新的代码,您将执行以下操作:
listOfDVDs list = new listOfDVDs();
while (sc.hasNext()) {
name = sc.next();
year = sc.nextInt();
director = sc.next();
//create a DVD.
DVD dvd = new DVD(name, year, director);
//add it to the list
list.add( dvd );
}
//return the result to the caller of the method.
return list;
推荐阅读
- python - Python & Selenium:发生 Selenium 异常时代码未执行
- javascript - 如何初始化一个有方法的类
- php - 使用 PHP-FPM 和 Apache 时如何立即发送 HTTP/2 标头
- django - 如何在 redoc API 文档上自定义 API 端点
- java - 使用 Greedy 找到最小浪费会给出不正确的输出
- mongodb - 如何从 MongoDb 函数中查询集合?
- c# - 如何将集合中的集合绑定到上下文菜单并通过单击获取上下文菜单项
- c# - 使用rotativa导出pdf时如何避免动态列表中的分页符?
- python - 如何使用python标记域和子域?
- angular - 如何在 Angular 中使用 ForkJoin 进行 POST 方法