gpt4 book ai didi

java - 返回对对象列表的引用

转载 作者:行者123 更新时间:2023-12-02 10:26:33 24 4
gpt4 key购买 nike

我创建了两个类: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 的类型吗?您可能只需要 DVDjava.util.List。您可以将其写为:

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;

关于java - 返回对对象列表的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53914378/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com