Michael D.
Michael D.

Reputation: 1837

How to dynamically address vars with a string?

Comming from Actionscript 3, Java seems to be a bit different here:

Having three Buttons, Button btn0; Button btn1; Button btn2; I want to iterate through them setting onClickListeners() like this:

for (int i=0; i < 4; i++) {    
    this["btn"+i].setOnClickListener(this);
}

is that even possible?

Upvotes: 1

Views: 48

Answers (1)

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 235984

Basically, you're asking about the data structures available in Java, let's see some options. It's possible to reproduce the behavior in your code if you use a Map:

// instantiate the map
Map<String, Button> map = new HashMap<String, Button>();
// fill the map
map.put("btn0", new Button());
// later on, retrieve the button given its name
map.get("btn" + i).setOnClickListener(this);

Alternatively, you could simply use the index as identifier, in which case it's better to use a List:

// instantiate the list
List<Button> list = new ArrayList<Button>();
// fill the list
list.add(new Button());
// later on, retrieve the button given its index
list.get(i).setOnClickListener(this);

Or if the number of buttons is fixed and known beforehand, use an array:

// instantiate the array
Button[] array = new Button[3];
// fill the array
array[0] = new Button();
// later on, retrieve the button given its index
array[i].setOnClickListener(this);

Upvotes: 3

Related Questions