返回对对象列表的引用

时间:2018-12-24 13:59:02

标签: 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;
}
  }

1 个答案:

答案 0 :(得分:1)

您需要一个名为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;
相关问题