0

I have an array

String[] strArray= {"Milk","Bread,"eggs"};

and generally we can display the values as strArray[i] in a loop ... however I am getting the name of the array " StrArray" dynamically from a value of a request parameter &arrayName=strArray .

request.getParameter("arrayName");

Can one of you experts kindly advise how to construct the arrayname from the request and use it to display the values of the array.

8
  • 1
    why do you want to do that? Commented Apr 12, 2017 at 15:38
  • You already know (and show) how to get the name from a parameter. Your best bet for accessing the array by dynamically-provided name is to store the array (and any others that you want to access that way) in a Map, with their names as keys. At runtime, retrieve them from the map. Commented Apr 12, 2017 at 15:39
  • based on request paramter I will have to display the values in my application , for example if the value of the request is strArray then will get the values displayed from strArray.. Commented Apr 12, 2017 at 15:39
  • If you're talking about doing this in a servlet / JSP, then you could consider storing the array as a request, session, or context attribute instead of in a Map. Commented Apr 12, 2017 at 15:40
  • @JohnBollinger can you give me an example? Commented Apr 12, 2017 at 15:41

2 Answers 2

0

The easiest but unclean way would be a map:

Map<String, String[]> map = new HashMap<String, String[]>();
map.put("strArray", strArray);
map.get("strArray");

Probably better would be to use reflection. stackoverflow example

Sign up to request clarification or add additional context in comments.

Comments

0
HashMap<String, String[]> strMap = new HashMap<String, String[]>();

strMap.put("strArray", new String[]{"Milk","Bread,"eggs"});

String strName[]=(String[])strMap.get(request.getParameter("strArray"));

response.write(strName[1]);

this works.

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.