Domanda

I'd like to write a program which creates a set of objects in a loop....

(i.e.)

String newFirm = "empty";

for(int i=0; i<30; i++)
    {
          newFirm = "firm" + i;
          firm newFirm = new firm();
    }

and then of course I would need something like

 stringToObject = "firm" + x;
 stringToObject.type = "service";
 stringToObject.size = 10000;

Obviously this code is fictional, but It expresses how I'd ideally create and call for objects. The nature of this program is such that the final number of firms (or other objects) are not known at the time of compiling.

Is there a method by which I can convert a given string into the name of an object (either to call or to create) as well as creating objects "on the fly"?

È stato utile?

Soluzione

Sounds like a job for an ArrayList.

ArrayList<Firm> myList = new ArrayList<Firm>();

And in your loop,

Firm firm = new Firm();
firm.type = "service";
myList.add(firm);

And to get it,

Firm f = myList.get(index);

Altri suggerimenti

convert a given string into the name of an object

Your need is to refer an object with the string in your hand. I'll suggest Hashmap<String,Object>

Eg:- you have a String,

String name="object_name";

And your class is Firm. Now,

Hashmap<String,Firm> objs=new Hashmap<String,Firm>();// note:your for loop comes after this line
Firm new_firm=new Firm();
new_firm.type = "service";
new_firm.size = 10000;
objs.put(name,new_firm);

Now you can refer your object with the string in your hand as

objs.get("object_name");
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top