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 ?
Asked
Active
Viewed 159 times
-4
-
Can you make your question more clear? – Thiyagu Sep 05 '15 at 16:32
-
I want to make an random named Object – battler3d Sep 05 '15 at 16:33
-
Why don't you generate a random string – Thiyagu Sep 05 '15 at 16:34
-
How can I make an Object from an String ? – battler3d Sep 05 '15 at 16:34
-
I meant `Map
map`. You create your object and a string and add to map. But why do you want to do this – Thiyagu Sep 05 '15 at 16:36 -
I wanted to acces it via a HashMap but I want do randomly create 20 Objects – battler3d Sep 05 '15 at 16:38
-
If you want to access it via a Map what should your key be? Why don't you put them in a List? – Thiyagu Sep 05 '15 at 16:40
-
I would take the Keys 1 2 3 ... – battler3d Sep 05 '15 at 16:41
-
1What do you mean by *random object*? Like 1st may be of `class A` the second of `class B` and so on? – Blip Sep 05 '15 at 16:42
-
I mean by random Object an Object with a String as name – battler3d Sep 05 '15 at 16:42
-
You want the variable names to be random? – Blip Sep 05 '15 at 16:45
1 Answers
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.