【问题标题】:Returning a reference to a list of objects返回对对象列表的引用
【发布时间】:2019-05-23 16:08:56
【问题描述】:

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

【问题讨论】:

  • 上面的代码也不能编译。请发布有效代码。
  • 为什么不使用列表而不是数组?
  • 尽我所能添加,数组是此任务的推荐方式
  • 清理你的代码以便我们理解它。 fromFile 在什么类?
  • 在 DVD 类列表中

标签: java


【解决方案1】:

您需要一个名为ListOfDVDs 的类型吗? 您可能只需要java.util.ListDVD。你可以这样写:

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-25
    • 2021-07-21
    • 1970-01-01
    • 2015-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多