Reputation: 11
Long time reader, first time query. I'm fairly new to java and I had a question specifically with using the comparator to compare dates from a yaml file that I saved as a linked hash map. After trying to use the comparator to sort the dates from my yaml file I received a ClassCastException: LinkedHashMap cannot be cast to Appointment
Here is the code:
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);
}
}
}
}
}
Any help is appreciated. Thanks again!
PS: Im using Snakeyaml if that makes any difference
Upvotes: 0
Views: 857
Reputation: 2905
lhm = (Map<String, List<Appointment>>)daysheet.load(reader);
This should be problematic statement . Here I think there is nothing wrong in comparator . daysheet.load(reader)
is not giving you a linked hashmap and you are trying to cast it in LinkedHashMap
Upvotes: 1