0

I have an array

String myArray[]={"one","two","three","four"};

In my code I am using a string with the same name as the array.Is there anyway to make that string point to the array?

String theArray = "myArray";

theArray[0];

Is this even possible?

2
  • myArray[0] will give the first index value "one", why do you want to place the variable name in the string? Commented Feb 13, 2011 at 15:25
  • I am getting a string from some user input.The string they input is the same as an array. Commented Feb 16, 2011 at 19:59

2 Answers 2

3

Is this even possible?

No.

You could use a Map<String, String[]> to map a name to an array.

A small example:

String[] myArray = {"one","two","three","four"};
Map<String, String[]> map = new HashMap<String, String[]>();
map.put("myArray", myArray);
String[] temp = map.get("myArray");
System.out.println(Arrays.toString(temp));

will print:

[one, two, three, four]
Sign up to request clarification or add additional context in comments.

2 Comments

can you please post an working example for this so that it can handy for future reference.
Thanks,What if we wanted to use the array itself.Like myArray[0].
1

If theArray is a field variable - yes, via reflection. But it is not advisable. Use a Map isntead.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.