james
james

Reputation: 2663

Make a string represent an array

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?

Upvotes: 0

Views: 884

Answers (2)

Bart Kiers
Bart Kiers

Reputation: 170158

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]

Upvotes: 3

Bozho
Bozho

Reputation: 597076

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

Upvotes: 1

Related Questions