长时间阅读,第一次查询。我对java很新,我有一个问题,特别是使用比较器来比较我保存为链接哈希映射的yaml文件中的日期。在尝试使用比较器对我的yaml文件中的日期进行排序后,我收到了ClassCastException:LinkedHashMap无法强制转换为约会
以下是代码:
import org.yaml.snakeyaml.*;
public class DaysheetGenerator {
public static void main(String[] args) throws Exception {
//Creates a string with the file name
String fileName = "resources/daysheet.yml";
//Creates a new yaml daysheet
Yaml daysheet = new Yaml();
// new instance of reader for YAML file
Reader reader = null;
try {
// pass yaml file into the reader to create a new instance of the YAML file for output
reader = new FileReader(fileName);
Map<String, List<Appointment>> lhm = new LinkedHashMap<>();
// casted a as Map during load, saved to variable lhm
lhm = (Map<String, List<Appointment>>)daysheet.load(reader);
// get the value based on the key, "appointments"
List<Appointment> list = lhm.get("appointments");
// sort the list of appointments by date
Collections.sort(list, new Comparator<Appointment>() {
@Override
public int compare(Appointment a1, Appointment a2) {
return a1.getDate().compareTo(a2.getDate());
}
});
// print list
System.out.println(list);
}
// if file cannot be found, print exception
catch (FileNotFoundException e) {
System.out.println("Could not find yaml file " + e);
e.printStackTrace();
}
finally
{
// close the reader after trying to read the file as long as the file exists
if (null != reader) {
try {
reader.close();
} catch(final IOException ioe) {
System.err.println("Recieved exception when trying to close reader" + ioe);
}
}
}
}
}
感谢任何帮助。再次感谢!
PS:我使用Snakeyaml,如果这有任何区别
答案 0 :(得分:1)
lhm = (Map<String, List<Appointment>>)daysheet.load(reader);
这应该是有问题的陈述。在这里,我认为比较器没有错。 daysheet.load(reader)
没有给你一个链接的hashmap,你试图在LinkedHashMap