【发布时间】:2019-12-29 15:23:16
【问题描述】:
我的程序解析一个 JSONArray,其中包含一个 JSONObejcts 列表,这些 JSONObejcts 是飞行员。然后它遍历并创建一个 Pilot 的新实例(它继承自 Crew 超类),并将其添加到名为 LoadedCrew 的 Crew 类型的 ArrayList 中(它的类型是 crew,因为机组人员也将添加到列表中)。
如下:
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);
}
当一个单独的方法在loadedCrew 列表中找到一个匹配条件的对象时,它应该返回一个名为pilotOutput 的Pilot (List) 类型的输出列表。 如下:
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;
}
但我收到以下错误:
...引发异常:java.lang.ClassCastException: class baseclasses.CabinCrew cannot be cast to class baseclasses.Pilot
我不明白为什么会发生这种情况,因为不仅对象已经是 Pilot 类型,而且当我将它分配给输出列表时,我什至将 Pilot 转换为它。我知道该方法不会尝试将任何cabineCrew 添加到列表中,因为我使用了 System.out.print(a) 来确保它只获取飞行员对象。
有什么想法吗?谢谢。
【问题讨论】:
-
pilotOutput 的类型是什么?
标签: java arrays json classcastexception