Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I name an array with a variable in java? [duplicate]

Tags:

java

arrays

for example I want to do this:

String[] arraynames = new String[2];
arraynames[0] = "fruits";
arraynames[1] = "cars";

and now I don't know how to do this

String[] arraynames[0] = new String[100]; // ??????

so that I create a String array called fruits with 100 cells... I know this doesn't work but is there someway to do this?

like image 442
Johny Avatar asked Nov 24 '10 21:11

Johny


1 Answers

Use an HashMap

Example:

HashMap<String,String[]> arraynames = new HashMap<String,String[]>();
arraynames.put("fruits", new String[1000]);

// then simply access it with
arraynames.get("fruits")[0] = "fruit 1";

However, may I suggest you replace arrays with ArrayList ?

HashMap<String,ArrayList<String>> arraynames = new HashMap<String,ArrayList<String>>();
arraynames.put("fruits", new ArrayList<String>());

// then simply access it with
arraynames.get("fruits").add("fruit 1");

** EDIT **

To have an array of float values instead of strings

HashMap<String,ArrayList<Float>> arraynames = new HashMap<String,ArrayList<Float>>();
arraynames.put("fruits", new ArrayList<Float>());

// then simply access it with
arraynames.get("fruits").add(3.1415f);
like image 80
Yanick Rochon Avatar answered Oct 14 '22 12:10

Yanick Rochon