使用for循环将ArrayList <long>转换为ArrayList <string>

时间:2017-03-09 20:13:36

标签: java arraylist

尝试此操作时,为什么会出现NullPointerException:

ArrayList<String> longsToStrings() throws IOException {
    LinkedList<Long> longNumbers = populateArrayWithLongs();
    ArrayList<String> strings = null;
    for (Long l : longNumbers) {
        strings.add(l.toString());
    }
    return strings;
}

当我尝试将结果打印到控制台时,我得到NullPointerException。 populateArrayWithLongs()函数返回带有long的数组:[1488758722000,1488773070000,1488787530000,1488801890000]

1 个答案:

答案 0 :(得分:0)

您只需要初始化字符串

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