首页 > 解决方案 > 返回对对象列表的引用

问题描述

我创建了两个类: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;
}
  }

标签: java

解决方案


你需要一个名为 的类型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;

推荐阅读