【问题标题】:ArrayList of PrintWriters and .get() methodPrintWriters 的 ArrayList 和 .get() 方法
【发布时间】:2016-04-13 11:29:55
【问题描述】:

我现在正在学习使用ArrayLists 和PrintWriters,我的教授给我们分配了一些东西,我们必须使用存储在ArrayList 中的多个PrintWriters 对文件进行分区.所以我用一个看起来像这样的for循环初始化Printwriters:

for (int i=1; i<=n; i++) {
  try {
    this.writers.add(new PrintWriter(new File(filePattern + i)));
  }
  catch (java.io.IOException e) {
    System.out.println("File " + i + " not found.");
  }
}

其中writersArrayList&lt;PrintWriter&gt;filePattern 是源。 但是在我的write 方法中,我必须调用这些PrintWriters 才能真正写东西。使用 int currentFile,我在文件中旋转以对它们进行分区,但是当我没有命名它时,我不确定如何使用 ArrayList 中的 PrintWriter。我可以按如下方式使用“get”方法吗? :

 public void write (String s) throws IOException {
  if (this.writers.size() > 0) {
    PrintWriter p = this.writers.get(currentFile);
    p.println(s);

    if (this.currentFile == (this.writers.size()-1)) {
      this.currentFile = 0;
    }
    else {
      this.currentFile++;
    }
  }
  else {
    System.out.println("No Writers currently exist");
  }
}

还是不行?如果没有,还有其他方法吗?

【问题讨论】:

    标签: java arraylist printwriter


    【解决方案1】:

    您可以执行this.writers.get(this.currentFile)this.writers[this.currentFile],如果您不检查this.currentFile 是否在0this.writers.size()-1 之间,仍然会导致IndexOutOfBoundsException。这应该适用于串行(即非并行)执行。

    此外,我建议使用 getter 访问您的数据(即 currentFile)并使用 setter 更改您的数据,即使在成员方法中也更简洁。

    【讨论】:

    • 嗯,是的,我习惯使用这些,但由于某种原因,他没有像上次作业中那样指定它,所以我觉得他可能希望我们避免使用它们一?我不知道,但我不想冒险。 .get() 应该可以工作吗?就像在我的示例中一样,它实际上应该可以正常运行?
    • @Azmera 如果您将一些对象引用放入 List 并希望通过索引访问这些对象引用,您可以使用显式 get 成员方法或重载 operator[] (这与“语法糖”完全相同”)。看看 API:docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
    猜你喜欢
    • 2013-02-13
    • 1970-01-01
    • 2015-05-15
    • 1970-01-01
    • 1970-01-01
    • 2016-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多