簡體   English   中英

無法訪問 Arraylist 內部的 object 屬性,另一個 Arraylist、ZD52387880E15EA22817A9813D

[英]Can't access object properties inside Arraylist inside another Arraylist, Java

這是創建對象的 class:

class cards_type{

String color;
String number;

public cards_type(final String input_color, final String input_number) {

    color = input_color;
    number = input_number;
}

}

這是 arraylist:

ArrayList<ArrayList>players_cards = new ArrayList<ArrayList>();
players_cards.add(new ArrayList<cards_type>());

當我添加值並使用此代碼打印時,它返回 object:

System.out.println(players_cards.get(0).get(0));

輸出:cards_type@ea4a92b

但是,如果我實例化一個屬性,它會返回一個錯誤,例如它不是 object:

System.out.println(players_cards.get(0).get(0).color);

OUT:線程“main”中的異常 java.lang.Error:未解決的編譯問題:顏色無法解析或不是字段

感謝幫助

這就是您應該如何修改代碼以使其工作的方式。

您初始化 ArrayList 的 ArrayList 的方式是錯誤的。 您應該始終提供要存儲在 arrayList 中的數據類型。

ArrayList<ArrayList<cards_type>> players_cards = new ArrayList<ArrayList<cards_type>>();

卡類型 class:

class cards_type {

    String color;
    String number;

    public cards_type(String input_color, String input_number) {

        this.color = input_color;
        this.number = input_number;
    }
}

測試 Class:

Class TestClass{
     public static void main(String[] args){
        ArrayList<ArrayList<cards_type>> players_cards = new 
  ArrayList<ArrayList<cards_type>>();
                cards_type pc = new cards_type("red","4");
                cards_type pc1 = new cards_type("black","2");
                cards_type pc2 = new cards_type("red","3");
                
                ArrayList<cards_type> al = new ArrayList<>();
                al.add(pc);
                al.add(pc1);
                al.add(pc2);
                
                players_cards.add(al);
                
                System.out.println(players_cards.get(0).get(0).color);
        }
    }

暫無
暫無

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

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