2

I have some Java code which contains some arrays. Say one of them is b. I have a string a whose value points to the names of those arrays at different times. So if a currently contains b, I want to access the 3rd element of b through a. Something which I could have done in Javascript with window[a][2]. is it possible in Java?

3
  • Using dynamic variable names is usually extremely inappropriate. Especially in a compiled language like Java. Commented Jan 15, 2013 at 11:18
  • I am actually using GWT. I have some custom drop-down menus, with the same functionalities for each, like dropdown, 'click`, etc. If I can't do this, I will have to write a separate handler for each, when all the handlers are exactly same save the name of the element they are dealing with.. Commented Jan 15, 2013 at 11:20
  • @Cupidvogel: Why don't your write the handler once, with a constructor that takes the array as a parameter and saves it in an instance variable and instantiate it many times? Commented Jan 15, 2013 at 11:24

2 Answers 2

1

Use collections. Looks like you're looking for HashMap

Something like that:

Map<String, List<String>> map = new HashMap<String, List<String>>();
Sign up to request clarification or add additional context in comments.

4 Comments

So you are suggesting that the keys will be the array names, while the values will be the arrays pointed to by them?
@Cupidvogel exactly. But instead of arrays you alson can use some collection. In the end your map will look like HashMap<String, ArrayList<T>> where T is the some type.
Yup, right. That was rather dumb of me to ask, since I already know Javascript internally uses hash to achieve this!
Map<String, List<String>>, why not a MultiMap (e.g. in Guava)
1

Based on your comments above, I'll give you a pseudo code answer:

Write the handler like this:

public class MyHandler implements YourHandlerInterface {

    private String[] array;

    public MyHandler(String[] array) {
        this.array = array;
    }
    // your methods that have to access the array.
}

Then, when you can use them somehow like:

fileMenu.addHandler(new MyHandler(fileMenuArray));
editMenu.addHandler(new MyHandler(editMenuArray));

So you don't use dynamically generated variable names and still only have to implement it once.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.