首页 > 解决方案 > 无法在另一个 Arraylist、Java 中访问 Arraylist 中的对象属性

问题描述

这是创建对象的类:

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>players_cards = new ArrayList<ArrayList>();
players_cards.add(new ArrayList<cards_type>());

当我添加值并使用此代码打印它时,它会返回对象:

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

输出:cards_type@ea4a92b

但是如果我实例化一个属性,它会返回一个错误,比如它不是一个对象:

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

OUT:线程“main”中的异常 java.lang.Error:未解决的编译问题:颜色无法解决或不是字段

感谢帮助

标签: javaobjectarraylistpropertiesinstance

解决方案


这就是您应该如何修改代码以使其工作的方式。

您初始化 ArrayList 的 ArrayList 的方式是错误的。您应该始终提供要存储在 arrayList 中的数据类型。

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

CardTypes 类:

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 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);
        }
    }

推荐阅读