I am trying to create new objects named cpu0, cpu1, ..., cpu8. The objects will be "Thread1_a" objects. I am getting a syntax error when I try to create the objects. Any help would be really appreciated!!
Jeff Ciaccio, Java novice <br />Physics and AP Physics Teacher<br />Sprayberry High School <br />Marietta, GA
Jeff Ciaccio wrote:I am trying to create new objects named cpu0, cpu1, ..., cpu8. The objects will be "Thread1_a" objects. I am getting a syntax error when I try to create the objects. Any help would be really appreciated!!
Use a Thread1_a or a Map<String,Thread1_a> instead:
Using a Map is the only way* to have dynamic variable names. The other solution, using an array, is similar; instead of your variables being named cpu0, cp1, etc, now they are called cpu, cpu, etc.
* Well, not the only one, but the other one involves generating code during runtime which is really not what you want to do.
Conceptually, the only reason you need to name a variable is because you're going to reference later on by that name. As Rob pointed out, the normal way to associate an object with a name is to use a Map, which stores a key value pair. In your case, the key is the String name, and the value is the associated Thread1_a instance. If you don't really care about the name, then you can just store them in a List. Your loop could store N Thread1_a instances in a List, and to reference those objects, you'd just loop through the list doing whatever you need to do.
It's hard to tell if you're just playing around with Java, or if you are actually trying to do things with threads. If you are trying to work with threads, then be aware that there is a ThreadGroup class that is designed to manage a collection of threads. That might be better than sticking them in a Map or List... (The thread classes are some of the oldest in Java, and consequently, have some old stuff in them, like the old Enumeration class. I think they were part of the early implementation because at that time Sun was pushing applets and its applet-empowered browser. Does anyone remember what that browser was called?)