List<Data> arrayListToFile = new ArrayList<>();
arrayListToFile.add(new Data("E30", "1985", ratingE30));
arrayListToFile.add(new Data("E36", "1992", ratingE36));
arrayListToFile.add(new Data("E46", "2000", ratingE46));
arrayListToFile.add(new Data("E92", "2007", ratingE92));
arrayListToFile.add(new Data("F80", "2014", ratingF80));
Path location = Paths.get("src/data.txt");
Charset utf8 = Charset.forName("UTF-8");
try {
write(location, arrayListToFile, utf8);
} catch (Exception e) {
System.out.println("The file could not be saved");
}
public static class Data {
private String name;
private String year;
private String rating;
public Data(String name, String year, String rating) {
this.name = name;
this.year = year;
this.rating = rating;
}
}
我不断收到不兼容类型的错误:
java.util.List<com.company.Main.Data> cannot be converted to java.lang.Iterable<? extends java.lang.CharSequence>
任何想法将不胜感激。
ArrayList
类是List
类的扩展,所以如果你要使用 ArrayList,那么完全使用它进行初始化。它可能不兼容,您可以在构造函数中指定子类的类型new ArrayList<Data>();
List<Data> arrayListToFile = new ArrayList<Data>();
或者只是将对象完全初始化为 ArrayList
ArrayList<Data> arrayListToFile = new ArrayList<>();