这是我的方法:
public static ArrayList collectSchedule(ArrayList schedule, ArrayList list, int counter)
{
((ArrayList) list.get(counter)).add(schedule);
System.out.println(list);
return list;
}
public static ArrayList getClassInfo(int count)
{
Scanner stdIn = new Scanner (System.in);
String userInput;
System.out.print("Enter the name of class #" + count + " : ");
userInput = stdIn.nextLine();
ArrayList x = getClassTime();
x.add(0, userInput);
x.add(1, getClassLength());
x.add(2, getDayOfTheWeek());
return x;
}
因此,我从 getClassInfo (这是一个 ArrayList)中获取值“x”,并将其与一个数字(我想要的位置的索引)和另一个 ArrayList (我们称之为“计划”)一起输入到方法collectSchedule中。我将“x”(ArrayList)添加到ArrayList“时间表”中。如果我打印出“x”,它将显示“schedule”的所有值。 (注意:我添加了多个不同的“x”实例来安排!)。因此,如果我将 3 个不同的“x”添加到“schedule”中,它将单独打印它们( [x, x, x][x, x, x][x, x, x] )。我无法从“schedule”中仅获取“x”的单个值。
我认为这段代码可以工作,但它在编译时给我一个错误。
public static void creation(ArrayList list)
{
System.out.println((schedule.get(0)).x().get(1));
}
谁能帮我解决我哪里出错了? 我读过一些关于使用对象的内容?但不知道如何!
谢谢!
最佳答案
如果您开始使用泛型,您会发现使用集合要容易得多,即 List<List<String>> myList
。此外,为什么不创建一些存储类型值的实际类而不是依赖索引列表呢?
除此之外......
System.out.println((schedule.get(0)).x().get(1));
如果 Schedule 的类型是 ArrayList,那么 Schedule.get(0) 将返回 Object 类型的内容,除非您执行显式强制转换。由于 Object 没有方法 x() ,因此会生成错误。您通常可以通过不在一行中包含如此多的链式函数调用来自行缩小范围。这样做会很难判断给定的错误指的是什么。
如果时间表声明为 List<List<String>>
甚至 List<List<Object>>
那么你就可以这样做:
List<String> classInfo = schedule.get(0);
String classLength = classInfo.get(1);
System.out.println(classLength);
我认为是你真正的目标
关于java - ArrayList 内的 ArrayList - 访问值时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13666419/