Jump to content

Dynamic variable names in Java

Go to solution Solved by Mr_KoKa,

If your names are in order like, 1, 2, 3 .. or 0, 1, 2 ... you can use ArrayList, examples described there: http://javarevisited.blogspot.com/2011/05/example-of-arraylist-in-java-tutorial.html

 

If your names aren't in order so there would be gaps between indexes, or if there are names other than numeric you can use HashMap: http://java67.blogspot.com/2013/02/10-examples-of-hashmap-in-java-programming-tutorial.html

 

Creating your ArraList remeber to provide valid type into <> brackets in Your case it will be <WebView> in case of ArrayList and <Integer, WebView> or <String, WebView> in case of HashMap.

I need a way to generate dynamicly named variable names.

 

Here is my code:

        for (int i = 0; i < size; i++) {            WebView Interger.toString(i) = makeWebView();        }

where "Interger.toString(i)" is the variable name i want. I could also change it to an actual string with an identifier i have, but i figured numbers were easy.

 

How would i go about doing this?

 

 

Thanks,

 

~Judah

~Judah

Link to comment
https://linustechtips.com/topic/300473-dynamic-variable-names-in-java/
Share on other sites

Link to post
Share on other sites

Use fixed size arrays if you know what its size will be ahead of creating, or some sort of vector/list/map ex. ArrayList.

 

Edit: If you need names other than numbers that can be turned into array index, use HashMap where key will be string, that way you can name element using letters too.

Link to post
Share on other sites

Use fixed size arrays if you know what its size will be ahead of creating, or some sort of vector/list/map ex. ArrayList.

 

 

The problem is, i cant use a fixed sized array because the number of webview elements i need to create is dynamic.

 

How would i go about a vector/list/map?

~Judah

Link to post
Share on other sites

If your names are in order like, 1, 2, 3 .. or 0, 1, 2 ... you can use ArrayList, examples described there: http://javarevisited.blogspot.com/2011/05/example-of-arraylist-in-java-tutorial.html

 

If your names aren't in order so there would be gaps between indexes, or if there are names other than numeric you can use HashMap: http://java67.blogspot.com/2013/02/10-examples-of-hashmap-in-java-programming-tutorial.html

 

Creating your ArraList remeber to provide valid type into <> brackets in Your case it will be <WebView> in case of ArrayList and <Integer, WebView> or <String, WebView> in case of HashMap.

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×