java - 无法在另一个 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:未解决的编译问题:颜色无法解决或不是字段
感谢帮助
解决方案
这就是您应该如何修改代码以使其工作的方式。
您初始化 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);
}
}
推荐阅读
- javascript - 谷歌地图 - addGeoJson 不适用于我的文件
- pandas - 更改图例的位置和条形图的大小
- c# - 为什么我在尝试使用 AddonSuccessListener 时收到 InvalidCastException?
- webhooks - FusionAuth:通过“设置密码”电子邮件确认时未触发 Webhook user.email.verified
- python-3.x - 将值作为 while 循环生成的行添加到 pd.dataframe
- amazon-qldb - QLDB 中的分页
- javascript - 将 gtag 事件从跨域发送到父域
- sql - 在存储过程中连接字符串
- docker - 找不到 Docker 主机证书身份验证凭据
- react-native - 在 ubuntu 上使用 Expo 时网络响应超时