Can I name an array with a variable in java?

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 it

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

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

+6
java arrays
source share
7 answers

Use 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, can I suggest you replace arrays with an 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); 
+15
source share

So, are you looking for a double indexed array?

Something like:

 String[][] arraynames = String[2][100]; 

In this case, you created an array of 2 arrays, each of which contains 100 String elements.

+1
source share

Hope I understood correctly, you could have something like this:

 ArrayList arraynames = new ArrayList(); arraynames.add("fruits"); arraynames.add("cars"); arraynames.set(0, new ArrayList(100) ); 
0
source share

I do not quite understand this second line of code. You said you were trying to create a string array called fruit. That would be enough if I understood it correctly.

 String [] fruits = new String[100]; 
0
source share

you should use a two-dimensional array as follows:

 String[][] myData = new String[2][100]; 

now myData is an array with 2 elements, both of which 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"; 
0
source share

Using the 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]}

0
source share

You can use one of the following actions:

 String[][] arraynames = String[2][100]; Map<String, String[]> namesMap = new HashMap<String, String[]>(); List<List<String>> names = new ArrayList<ArrayList<String>()>>(); 
0
source share

All Articles