Reputation: 15
I have a method that receives an array of strings and I need to create objects with appropriate names.
For example:
public class temp {
public static void main(String[] args){
String[] a=new String[3];
a[0]="first";
a[1]="second";
a[2]="third";
createObjects(a);
}
public static void createObjects(String[] s)
{
//I want to have integers with same names
int s[0],s[1],s[2];
}
}
If I receive ("one","two") I must create:
Object one;
Object two;
If I receive ("boy","girl") I must create:
Object boy;
Object girl;
Any help would be appreciated.
Upvotes: 0
Views: 145
Reputation: 7899
First create Map
which contains the key as String representation of Integers
.
public class Temp {
static Map<String, Integer> lMap;
static {
lMap = new HashMap<String, Integer>();
lMap.put("first", 1);
lMap.put("second", 2);
lMap.put("third", 3);
}
public static void main(String[] args) {
Map<String, Integer> lMap = new HashMap<String, Integer>();
String[] a = new String[3];
a[0] = "first";
a[1] = "second";
a[2] = "third";
Integer[] iArray=createObjects(a);
for(Integer i:iArray){
System.out.println(i);
}
}
public static Integer[] createObjects(String[] s) {
// I want to have integers with same names
Integer[] number = new Integer[s.length];
for (int i = 0; i < s.length; i++) {
number[i] = lMap.get(s[i]);
}
return number;
}
}
Upvotes: 0
Reputation: 6987
Can't do that in java. You can instead create a Map
who's keys are the strings and the values are the objects.
Upvotes: 7