【问题标题】:How to access elements of a dynamic array of string arrays in java?如何在java中访问字符串数组的动态数组的元素?
【发布时间】:2012-11-10 23:17:27
【问题描述】:

我正在尝试使用 opencsv (http://opencsv.sourceforge.net/)。 opencsv 的下载中包含示例。以下是他们创建动态数组示例的摘录:

CSVReader reader = new CSVReader(new FileReader(ADDRESS_FILE));
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
    System.out.println("Name: [" + nextLine[0] + "]\nAddress: [" + nextLine[1] + "]\nEmail: [" + nextLine[2] + "]");
}

它读取的CSV文件如下:

Joe Demo,"2 Demo Street, Demoville, Australia. 2615",joe@someaddress.com
Jim Sample,"3 Sample Street, Sampleville, Australia. 2615",jim@sample.com
Jack Example,"1 Example Street, Exampleville, Australia. 2615",jack@example.com

如果我将 println 语句移到 while 循环之外,我会在 Eclipse 中收到错误:“空指针访问:变量 nextLine 在此位置只能为空。”

我的猜测是 nextLine 有一个指针当前指向它的最后一个位置或超过它的最后一个位置。我想我的问题是,我如何控制那个指针?

【问题讨论】:

  • 不,你误解了这里的错误。由于您的循环条件是一直持续到nextLine == null,因此之后您可以保证它将是null,这就是Eclipse 抱怨的原因。您必须在循环中使用变量或更改您的条件。

标签: java arrays pointers dynamic


【解决方案1】:

nextLine == null 时,您退出循环。因此,当您将println 语句移出循环时,nextLine 就是null。错误"Null pointer access: the variable nextLine can only be null at this location." 完全有道理。

要访问您在循环之后读取的所有内容,您可以执行以下操作:

在进入循环之前添加:

List<String[]> readLines = new ArrayList<>();

在循环中这样做:

readLines.add(nextLine);

因此,在循环之后,您可以从 readLines 列表中读取所有已读取的行。

【讨论】:

  • 哦!所以写的代码丢弃了所有读取的行,对吗?它只是在每次迭代中不断覆盖同一个数组,然后在最后一次迭代中它会将 null 写入该数组?非常感谢!
  • 您为每个读取行创建一个新数组,但在下一次迭代中丢失(覆盖)对它的引用。因此,您的读取行可能仍在内存中,但它们有资格进行垃圾收集,您无法再访问它们。在代码中的最后一次循环迭代之后,您的引用将指向 null,并且您无法再访问任何行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多