-4

I would like to make a few Objects and then add them to a HastMap. I dont want to name all of these Objects by Hand so I would do it in a for Loop. Any ways to solve this ?

battler3d
  • 3
  • 4

1 Answers1

0

What you are looking for is called a "variable variable". Java doesn't support these, but some languages, like PHP, do. You can create a HashMap of objects with generated keys, however, like this:

Map<String, Object> map = new HashMap<String, Object>;
// makes a HashMap of strings to objects;
// if you want to use something else for the keys,
// you can change the first type name between the <>

map.put("key", object);
//adds an object to the HashMap for the key "key"

and then get the objects back from the map like this:

map.get("key");
//will return object

If you want to do this in a for loop, you'd do something like this:

Map<String, Object> map = new HashMap<String, Object>;
String[] keys = {"foo", "bar", "food", "bard", "fooley", "barley"};
for(int i = 0; i < keys.length; i++) {
    map.put(keys[i], myObject);
}

This answer is a way to generate those strings randomly.

Community
  • 1
  • 1
xǝlɐ
  • 63
  • 1
  • 11