Create a variable using a String for the name
I want to create a variable, but use a string as the name.
I have a program that will parse a user-generated file. The user can create names for each of the parts, and I want to be able to preserve those names as the variable names. There is an unlimited number of parts each file can have. The only way I can think of to create my variables is to create each one separately, but I don't want to type forever.
I want to do something like
for( int i = 0; i < numParts; i++ ) {
String s = new String("part" + i);
Vector (s) = new Vector();
}
Is there any way at all to do something like that?
Not sure where you are going with this. You may want to check out [url http://java.sun.com/j2se/1.5.0/docs/api/java/util/Map.html]java.uitl.Map[/url].
This question comes up from time to time and I will say what I always say.
Your design thinking is flawed and I recommend rethinking. How could you for example easily store the items in a Collection and then retrieve and work with the right one?
If you don't want to go that route (which is the right one) then shove everything in a map and use the Strings for the keys.
Assuming I understand your question:
Do a search on these forums and you will find many threads on this subject.
The bottom line is that you cannot do this in Java; however, the good news is that you almost (never) need to do this.
Using a Map is often the suggest solution and in your case you may be able to use an ArrayList. And I am sure there are other solutions.
jbisha at 2007-7-14 22:31:31 >

Follow the example in this thread (which uses textfields):
http://forum.java.sun.com/thread.jspa?threadID=634815
Do not use:
new String("part" + i)
The following is sufficient:
"part"+i
Look into using ArrayList instead of Vector. If you need the synchronization, use Collections.synchronizedList around your ArrayList.
MLRona at 2007-7-14 22:31:31 >

Alright, I'll try a HashMap now. Though if you believe I am wasting your time by asking a question that has already been asked, you need not bother answering me.I'll repost when I've finished and tell if it worked...
> Alright, I'll try a HashMap now.
> Though if you believe I am wasting your time by
> asking a question that has already been asked, you
> need not bother answering me.
>
Holy **** dude. Chill out.
I am mentioning that it is a common misconception/problem and one that is better resolved from the design persepctive.
The REASON I mentioned that is that if I just say "your design needs adjustment" the common response is "you don't understand what I am asking" to which I reply "well actually I think I do because this is a common problem" etc.
So I wanted you to know that you weren't the first person to have this problem. And no It can't be solved by searching really because if you knew what you were looking for in terms of design you wouldn't have this problem.
> Though if you believe I am wasting your time by
> asking a question that has already been asked, you
> need not bother answering me.
You know, usually people appreciate when they're told that they're making mistakes. Do you tell that to your friends too? "If you think I annoyed you, you don't need to bother telling me?"
> You know, usually people appreciate when they're told> that they're making mistakes. Do you tell that to> your friends too? "If you think I annoyed you, you> don't need to bother telling me?"Ola! 縏odo bien?
What do you think has so many people asking this question?
Its as if with new programmers theres a large disconnect between
compile time and runtime.
Maybe they cant visualize the object creation?
With a lot of them it seems like they cant make the connection that
you can have more objects ("variables" they call them) then you explicitly code.
I guess im just curious about the origin of this issue. It seems like a lot of people struggle with it.
> What do you think has so many people asking this
> question?
I think it is a phase of learning to Java/OO program. It's hard to remember once you do know a time that you didn't know but once you have this "ah-ha" moment you just think that way permanently I think.
The way I see it is that there are the following stages of Java/OO design and programming enlightenment.
Stage 1: Everything is in static methods in once class. Basically a procedural program written in Java.
Stage 2: Understanding objects a bit more and starting to use them.
Stage 3: Understanding the true power of Collections.
Stage 4: Finding interfaces and starting to use them.
Stage 5: Refactoring
Stage 6: Uses abstract classes appropriatley
Stage 7: I don't know quite what to say here but you'll know you are here when you spend a lot of time debating jschell, dubwai, saish, and duffymo in the OO Design forum about the use of various patterns.
I think this person is transitioning from stage 2 to stage 3.
Yea im working hard at 5 presently. D@mn.I wanted to debate jschell, dubwai, saish, and duffymo now : )Im interface crazy but i dont think ive ever used a single abstract class.
> Yea im working hard at 5 presently.
> D@mn.
> I wanted to debate jschell, dubwai, saish, and
> duffymo now : )
>
This never stopped daFei (who is actually stage - 3 although he thinks it's the secret 11th stage)....
> Im interface crazy but i dont think ive ever used a
> single abstract class.
Yes. I didn't use to use them much. Now I use them more. Often for code reuse for interface implementations where I find that the implementations have similar portions.
> What do you think has so many people asking this> question?There are some languages which allow for dynamic variables that can do such things. I haven't used Perl in years, but I think it has this functionality.
How would that work?Does the variable then belong to a class or a collection or what?
> > What do you think has so many people asking this
> > question?
>
> There are some languages which allow for dynamic
> variables that can do such things. I haven't used
> Perl in years, but I think it has this functionality.
Many languages have hash indexed arrays. That's what accomplishes this and you can accomplish the same in Java.
Something else
colorArray["green"] = "00FF00";
colorArray["blue"] = "0000FF";
Java
Map colorMap = new HashMap();
colorMap.put("green","00FF00");
colorMap.put("blue","0000FF");
> How would that work?
> Does the variable then belong to a class or a
> collection or what?
See my last post.
What is happening is that the "array" in the other language (and note how this is more likely to be found in an interpreted language) is in fact backed by something like HashMap.
If you pass in a string (or other object) it uses that as a key. You can often use it as an array as well (in which case you work with an enumeration of values of the Map).
> How would that work?
> Does the variable then belong to a class or a
> collection or what?
I believe this type of thing is usually in scripting languages. I have used something like it in Clipper (a DBase compiler). Also, some OS command interpreters allow something like this (Unix eval, MPE/XL variable dereferencing).
But I think I am just showing my age.
jbisha at 2007-7-21 10:31:52 >

In fact some interpreted languages don't have actual arrays at runtime at all but only these Hashmaps (in which the keys are index numbers like 0,1,2 etc)JavaScript works like this (at least the MS implementation does).
> > What do you think has so many people asking this
> > question?
>
> There are some languages which allow for dynamic
> variables that can do such things. I haven't used
> Perl in years, but I think it has this functionality.
Indeed, as does PHP
http://us2.php.net/variables.variable
and LISP, Ruby and JavaScript (at least) via the eval keyword. So folk coming from there would already be thinking that way.
tsitha at 2007-7-21 10:31:52 >

> How would that work?
> Does the variable then belong to a class or a
> collection or what?
I don't remember much of the Perl syntax but I think you can do something like (pseudocode):
$foo = 1;
$variableName = "foo";
print "The value of the variable is ${$variableName}";
// OUTPUT: The value of the variable is 1
Close, but it's
no strict refs;
$foo = 1;
$variableName = "foo";
print "The value of $variableName is ", $$variableName, "\n";
This is called a symbolic reference, and you aren't really supposed to use them. At any rate, it's pretty much meaningless to develop Java code that does the same thing. If you truly needed dynamic code, you'd probably use Dynamic Proxies or a Decorator pattern or something to that effect.
Brian
> no strict refs;
>
> $foo = 1;
> $variableName = "foo";
> print "The value of $variableName is ",
> $$variableName, "\n";
That can get very ugly. Out of curiousity, is something like this valid:
no strict refs;
$one = 1;
$two = "one";
$three = "two";
$four = "three";
print $$$$four, "\n"; //uhhhg
> That can get very ugly. Out of curiousity, is
> something like this valid:
> no strict refs;
> $one = 1;
> $two = "one";
> $three = "two";
> $four = "three";
> print $$$$four, "\n"; //uhhhg
Just tested it. It does work. Forgot I had a Perl interpreter on my machine.
> Close, but it's
> no strict refs;
>
> $foo = 1;
> $variableName = "foo";
> print "The value of $variableName is ",
> $$variableName, "\n";
Actually, I just ran my earlier code and it also worked. Maybe it's the version of Perl. I'm just surprised I still remembered that much. Ok, I've digressed, this is a Java forum.
Many interpreted languages allow the program to define more program on the fly. It's a very powerful technique, but also prone to serious abuse and a source of some of the most intractable bugs. It also make code analysis nearly impossible.
As far as where the function or variable gets defined, that's up to the language, older languages usually defined them as globals, newer ones as local to a function or the closest class.
You can do this for classes in Java by invoking the complier and then loading the class. Redefining a class is much trickier, as I recall it involves messing around with class loaders. There was a thread on this topic several years ago.