Can I name an array with a variable in java? [duplicate]
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?
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);
So, you are looking for a doubly indexed array?
Something like:
String[][] arraynames = String[2][100];
You have created an array of 2 arrays that contain 100 String elements each in this case.
I hope I get you right, you could something like this:
ArrayList arraynames = new ArrayList();
arraynames.add("fruits");
arraynames.add("cars");
arraynames.set(0, new ArrayList(100) );
I am not quite clear on the second line of code here. You said you are trying to create a string array named fruits. This should suffice if I understood this right.
String [] fruits = new String[100];
you should use a bi-dimensional array like this:
String[][] myData = new String[2][100];
now myData is an array with 2 elements, both of them are arrays of "100 cells", then you can use these 2 arrays as follows:
String[] fruits = myData[0];
String[] cars = myData[1];
fruits[0] = "peach";
cars[0] = "mustang";
Using Guava library:
ListMultimap<String,String> mappedItems = ArrayListMultimap.create();
mappedItems.put("Fruits","Apple");
mappedItems.put("Fruits","Orange");
mappedItems.put("Fruits","Banana");
mappedItems.put("Cars", "BMW");
mappedItems.put("Cars","Ferrari");
System.out.println(mappedItems);
Output:
{Cars=[BMW, Ferrari], Fruits=[Apple, Orange, Banana]}
You can use one of the following :
String[][] arraynames = String[2][100];
Map<String, String[]> namesMap = new HashMap<String, String[]>();
List<List<String>> names = new ArrayList<ArrayList<String>()>>();
精彩评论