简体   繁体   中英

Can't access object properties inside Arraylist inside another Arraylist, Java

This is the class that creates the objects:

class cards_type{

String color;
String number;

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

    color = input_color;
    number = input_number;
}

}

And this are the arraylist:

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

When I add the values and print it with this code, it returns the object:

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

OUT: cards_type@ea4a92b

But if I instance a property it returns a mistake like if it wasnt a object:

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

OUT: Exception in thread "main" java.lang.Error: Unresolved compilation problem: color cannot be resolved or is not a field

Thanks for help

This is how you should modify your code to make it work.

The way you initialized the ArrayList of ArrayList was wrong. You should always provide the type of the data you want to store in the arrayList.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM