所以我有一个 GeneralTemplate 类和一个扩展 GeneralTemplate 的运动类。
从我包含的 GeneralTemplate 代码中可以看出,每个扩展它的类(其中有几个)都包含一个 ArrayList
当我到达这条线...
Exercise chosenExercise = (Exercise) FitnessApp.routineList.get(chosenRoutinePosition).getItem(chosenWorkoutPosition).getItem(chosenExercisePosition);
我收到以下错误ClassCastExceptionjava.lang.ClassCastException: com.karibastudios.gymtemplates.GeneralTemplate cannot be cast to com.karibastudios.gymtemplates.Exercise
我不明白为什么这是因为练习是 GeneralTemplate 的子类?
通用模板代码:
public class GeneralTemplate
{
private String name;
private ArrayList <GeneralTemplate> items; // Generic items list
// Super constructor for all subclasses
public GeneralTemplate(String name)
{
this.setName(name);
items = new ArrayList<GeneralTemplate>();
}
// Only sets will differ
public void addItem(String newName)
{
items.add(new GeneralTemplate(newName));
}
// Remove item at position
public void removeItem(int position)
{
if (items.size() > 0 && position <= items.size())
items.remove(position);
}
// Remove all items
public void removeItems()
{
items.clear();
}
/* ****************** GETTERS AND SETTERS START ********************/
// Get item
public GeneralTemplate getItem(int position)
{
return items.get(position);
}
// Set list of objects e.g Routines, Workouts, Exercises
public void setItems(ArrayList <GeneralTemplate> items)
{
this.items = items;
}
// Return item list
public ArrayList <GeneralTemplate> getItems()
{
return items;
}
// Return name
public String getName()
{
return name;
}
// Set name
public void setName(String name)
{
this.name = name;
}
/* ****************** GETTERS AND SETTERS END ********************/
}
尝试强制转换 GeneralTemplate 以调用方法的异常代码
chosenRoutinePosition = getIntent().getIntExtra("chosen_routine", 0);
chosenWorkoutPosition = getIntent().getIntExtra("chosen_workout", 0);
chosenExercisePosition = getIntent().getIntExtra("chosen_workout", 0);
// Navigates through the Routine List and gets the chosen routine
chosenExercise = (Exercise)FitnessApp.routineList.get(chosenRoutinePosition).getItem(chosenWorkoutPosition).getItem(chosenExercisePosition);
练习类非常简单,并通过一些额外的方法扩展了 GeneralTemplate
这有点绊脚石,任何帮助都会很棒。
干杯