所以我有一个2元素的Object数组,其中第一个元素应该存储学生对象的arrayList,然后将Object数组作为参数传递给另一个,例如说" X"方法现在从该Object数组1st元素访问arrayList元素并将其添加到另一个列表中。 我所做的是,在我的代码中我有
List<Student> students = new ArrayList<>();
//And then I create student objects
//I have a For loop
Student s = new Student( //add student object)
//Add student objects to list
students.add(s);
//Now for loop is done and now I assign Object array 1st element to students
o[1]=students;
//pass the object array to a method
MainActivity.x(o); //This is from postExecute
//Method declaration in MAINACTIVITY class
//In main Program class List<Student> studentList = new ArrayList<>(); is declared
public void x(Object[] res)
{
studentList.add((Student)res[1]);
}
问题在于获得类强制转换异常。我认为有些事我做错了。提前谢谢。
答案 0 :(得分:0)
您的代码存在两个问题:
(1)您正在分配List<Student>
并传递给x
方法,因此您无法将Student
转换为类型,即您只能转换为列表
(2)数组索引以 0 开头,因此使用索引0而不是索引1分配第一个元素
代码如下所示,带有内联注释:
List<Student> students = new ArrayList<>();
Student s = new Student();
students.add(s);
Object[] objects = new Object[2];
o[0]=students;//assigning list
MainActivity.x(o);
public void x(Object[] res) {
List<Student> studentsList = (List<Student>)res[0];//typecast to List only
//studentList.add();
}
另外,作为旁注,我强烈建议您正确命名变量,以便它们易于阅读,并且可以轻松检测到错误,即如果您将变量命名为{{1 }},s
,其他人不会非常清楚地遵循您的代码(因此,请从较小的案例开始命名,例如o
,student
等。)。
答案 1 :(得分:0)
由于您的作业ClassCastException
,您收到了o[1]=students
。这会将List<Student>
放入数组中,而方法x
则需要Student
位于该位置。
我认为您需要的是以下内容:
public void x(Object[] res) {
studentList.add(((List<Student>)res[1]).get(0));
}
答案 2 :(得分:0)
首先,有几种更好的方法可以满足您的需求 但是这段代码中的错误是
public void x(Object[] res)
{
studentList.addAll((List<Student>)res[1]);
//you are passing an array list not an object that is why is is causing a cast exception
}
也请显示o的初始化 我建议创建一个包含学生的arraylist和你想传递的任何其他元素的类,并将该对象传递给方法
喜欢
class DataStudents {
public ArrayList<Student> students;
public String anyOtherData;
}
并将其传递给
public void x(DataStudents res)
{
studentList.addAll(res.students);
}
答案 3 :(得分:0)
而不是在最后一次转换为ArrayList时转换为Student。