首页 > 解决方案 > 如何从文件中读取 ArrayLists 列表?

问题描述

我正在尝试读取包含图形邻接列表的文件。该文件如下所示:

1 2 3 5
2 4
3 1 5
4 
5 2 4

每行都是一个链表,其长度与其他行不同。到目前为止,我试过这个:

private static List<ArrayList<String>> adj;

ArrayList<String> rows = new ArrayList<String>();

int i = 0;
try {
    Scanner input = new Scanner(new BufferedReader(new FileReader(fileName)));
    //BufferedReader input = new BufferedReader(new FileReader(fileName));

    String line;
    while (input.hasNextLine()){
        i++;
        String[] cols = input.nextLine().trim().split(" ");
        for (String c : cols){
            rows.add(c);
        }
        adj.add(rows);
    }

    //print the matrix
    for (List<String> list : adj) {
        for (String str : list) {
            System.out.print(str + " ");
        }
        System.out.println();
    }
}
catch (IOException e){
    System.out.println("Error reading input file!");
}

但它不起作用,因为当我尝试打印整个矩阵时它显示错误(NullPointerException)。如何正确读取此文件?

标签: javalistarraylist

解决方案


编辑 我复制了您的代码,对列表进行了初始化,添加了 try/catch 并添加了打印代码,这工作正常:

List<ArrayList<String>> adj = new ArrayList<>();

int i = 0;

Scanner input = null;
try {
    input = new Scanner(new BufferedReader(new FileReader(fileName)));
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

String line;
while (input.hasNextLine()) {
    ArrayList<String> rows = new ArrayList<String>();
    i++;
    String[] cols = input.nextLine().trim().split(" ");
    for (String c : cols) {
        rows.add(c);
    }
    adj.add(rows);
}

for (ArrayList<String> list : adj) {
    for (String s : list) {
        System.out.print(s + " ");
    }
    System.out.println();
}

推荐阅读