0

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.

2
  • Probably you haven't yet used the collection framework available in Java. Commented Jul 10, 2012 at 10:57
  • 1
    What do you mean, "with appropriate names"? Are you trying to create objects which have a name property? Or do you actually want to have classes called "first", "second", etc? What have you tried so far? Commented Jul 10, 2012 at 10:57

2 Answers 2

7

Can't do that in java. You can instead create a Map who's keys are the strings and the values are the objects.

Sign up to request clarification or add additional context in comments.

2 Comments

but I don't know with which names create objects, it will be known only at execution
the map IS populated at runtime.
0

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;
}

}

1 Comment

you misunderstand me :) integers are examples. I mean: if I receive ("one","two") I must create: Object one; Object two; if I receive ("boy","girl") I must create: Object boy; Object girl;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.