我正在编写一些 Java 代码,将数据文件的每一行读入数组列表,对该列表进行混洗,然后对混洗后的数据执行一些进一步的操作。问题是,在洗牌之后,我得到了数组列表中某些元素的空元素。
//this file contains the data
String input = ...;
//this file contains the number of rows in the data file
String input2 = ...;
FileInputStream fstream2 = new FileInputStream(input2);
DataInputStream in2 = new DataInputStream(fstream2);
BufferedReader brIndex = new BufferedReader(new InputStreamReader(in2));
for(int i = 1; i <= N; i++) {
FileInputStream fstream = new FileInputStream(input+(i+1)+".txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader brData = new BufferedReader(new InputStreamReader(in));
num = Integer.parseInt(brIndex.readLine());
ArrayList<String> temp = new ArrayList<String>();
for(int j = 0; j < num; j++) {
temp.add(brData.readLine());
}
brData.close();
Collections.shuffle(temp);
//read in shuffled data
for(int j = 0; j < num; j++) {
rowData = temp.get(j); ...
}
在执行代码时,在使用 rowData
时,我在此之后收到一个 NullPointerException
。原始文件有 17,169 行(没有一行为空)。 temp.size()
也是 17,169,但是当我将 temp 打印到控制台时,temp.get(j)
对于某些 j
为 null而不是为了其他人。
谁能向我解释一下为什么会出现这种情况以及如何避免这种情况?
最佳答案
问题可能是文件中没有足够的行作为 num
。
尝试:
List<String> temp = new ArrayList<String>();
String line;
while((line = br.readLine()) != null) {
temp.add(brData.readLine());
}
您还可以在实际随机播放列表之前检查列表中是否有空元素,因为随机播放不会向列表中插入任何新元素。
关于java - 为什么 Collections.shuffle(List) 之后会出现空行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8809941/