My program parses a JSONArray containing a list of JSONObejcts which are pilots. It then iterates through and creates a new instance of a Pilot (which inherits from Crew superclass) and adds it to an ArrayList of type Crew called loadedCrew (it's of type crew as cabin crew also will be added to the list).
As follows:
JSONObject crew = new JSONObject(json); //Create a new JSONObject called root from the json file stored in 'json'
JSONArray allPilots = crew.getJSONArray("pilots");
JSONArray allCabinCrew = crew.getJSONArray("cabincrew");
for (int i = 0; i < allPilots.length(); i++) {
Pilot a = new Pilot();
JSONObject pilot = allPilots.getJSONObject(i);
JSONArray typeRatings = pilot.getJSONArray("typeRatings");
a.setForename(pilot.getString("forename"));
a.setSurname(pilot.getString("surname"));
a.setHomeBase(pilot.getString("homebase"));
a.setRank(Pilot.Rank.valueOf(pilot.getString("rank")));
for(int i1=0; i1 < typeRatings.length(); i1++)
{
a.setQualifiedFor(typeRatings.getString(i1));
}
loadedCrew.add(a);
}
A separate method then should return an output list of type Pilot (List) named pilotOutput when it finds an object in the loadedCrew list that matches the criteria. As follows:
public List<Pilot> findPilotsByTypeRating(String typeCode) {
// TODO Auto-generated method stub
pilotOutput.clear();
for(Crew a : loadedCrew)
{
if (a instanceof Pilot && a.getTypeRatings().contains(typeCode));
{
pilotOutput.add((Pilot)a);
}
}
return pilotOutput;
}
But I get the following error:
...threw an exception: java.lang.ClassCastException: class baseclasses.CabinCrew cannot be cast to class baseclasses.Pilot
I can't understand why this happens because not only is the object already of type Pilot, I'm even casting Pilot to it when I assign it to the output list. I know the method is not trying to add any cabinCrew to the list because I've used System.out.print(a) to ensure it's only getting pilot objects.
Any ideas? Thanks.
Remove the semicolon at the end of your if
line. It should be like this:
if (a instanceof Pilot && a.getTypeRatings().contains(typeCode))
pilotOutput.add((Pilot) a);