簡體   English   中英

ArrayList 中的 ArrayList - 訪問值時遇到問題

[英]ArrayList inside ArrayList - Trouble Accessing Values

所以這是我的方法:

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(我們稱之為“schedule”)一起輸入到方法 collectSchedule 中。 我將“x”(ArrayList)添加到 ArrayList“schedule”。 如果我打印出“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 ,您會發現使用集合會容易List<List<String>> myList 此外,為什么不創建一些實際的類來存儲類型值而不是依賴索引列表?

那一邊……

System.out.println((schedule.get(0)).x().get(1));

如果 schedule 的類型是 ArrayList,那么 schedule.get(0) 將返回 Object 類型的內容,除非您執行顯式轉換。 由於 Object 沒有方法 x() 會產生錯誤。 您通常可以通過不在一行中包含如此多的鏈式函數調用來縮小這些內容的范圍。 這樣做會導致很難分辨給定的錯誤所指的是什么。

如果 schedule 被聲明為List<List<String>>甚至List<List<Object>>那么你就可以這樣做:

List<String> classInfo = schedule.get(0);
String classLength = classInfo.get(1);
System.out.println(classLength);

認為這就是你真正的目標

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM