2

Is it possible to use a variable name to manipulate an array?

For example:

String addto = "database";
database = new String[2]; 

I want to add values into the array named "database", which has only 1 column.

Would it be possible to do something like...

addto[0] = hi;
addto[1] = hi1;

instead of

database[0] = hi;
database[1] = hi1;

etc? Use the value inside "addto" ("database") to manipulate the array?

Thanks!

edit: changed String addto to "database" (with "")

13
  • Is the array name, e.g., database, coming from user input, or what? Commented Jul 26, 2012 at 17:53
  • Yes it is coming from user input Commented Jul 26, 2012 at 17:53
  • 1
    You may look for reflections docs.oracle.com/javase/tutorial/reflect/special/… and java.sun.com/developer/technicalArticles/ALT/Reflection Commented Jul 26, 2012 at 17:54
  • How many arrays do you have? Could you manually add them to a Map<string, object[]>, for instance, to link a name to the actual array? Commented Jul 26, 2012 at 17:54
  • 1
    Okay why don't you just do String[] addto = database? Is that what you want to do? Commented Jul 26, 2012 at 18:02

2 Answers 2

5

You'd want to use something like:

Map<String, String[]> arrays = new HashMap<String, String[]>();
arrays.put("database", new String[2]);

...

map.get(addTo)[0] = hi;
map.get(addTo)[1] = hi1;
Sign up to request clarification or add additional context in comments.

2 Comments

does this create a new array named "database"?
@01jayss: No, objects don't have names. It creates a new array, and make that the value associated with the key "database" in a map.
0
String addto = "database"; 
database = new String[2];  
addto[0] = hi;  
addto[1] = hi1;

This code will not compile because addto is a String and does not support indexing with []. To do something similar to this, you can use a java.util.Map as illustrated by Jon Skeet.

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.