JTalbott
JTalbott

Reputation: 81

Minimal lines for declaring a bunch of similar variables

I'm making a chess board in Android Studio, and I have a button for each square. 64 variables. How can I initialize all of these at the beginning of my class without taking up 64 lines?

I tried putting the variables in a block of code enclosed by { ... }, but it said I wasn't allowed to.

private Button a1;
private Button a2;
private Button a3;
private Button a4;
private Button a5;
private Button a6;
private Button a7;
private Button a8;

I would like to have it so that I can click a drop down arrow on the left side of my screen that will make all of these variables disappear until I need to look at them.

Upvotes: 1

Views: 59

Answers (1)

hmanolov
hmanolov

Reputation: 113

You might want to use an Array or ArrayList in this particular case.

For ArrayList you can do:

private ArrayList<Button> a = new ArrayList<Button>();
for(int i = 0; i < 64; i++)
    a.add(new Button());
System.out.println(a.get(0));

The above gives you flexibility on removing or adding buttons. To keep track of buttons by name instead of index you can use HashMap

For HashMap you can do:

private HashMap<String, Button> a = new HashMap<String, Button>();
for(int i = 0; i < 64; i++)
    a.add("Button"+String.valueOf(i), new Button());
System.out.println(a.get("Button0"));

Upvotes: 3

Related Questions