Reputation: 3320
I need to store values specific to a username into memory, I was thinking about something like dynamically naming vars, so that I could do something like
["bubby4j_falling"] = true;
and index it by
["bubby4j_falling"]
But, this is just a example, I know that won't work, I just want a way to quickly and simply get and store things dynamically.
Upvotes: 0
Views: 129
Reputation: 718886
@Paŭlo Ebermann's answer is spot on.
I just want to point out that the Java language has nothing that resembles a dynamic variable. All Java variable names and their types are declared in the Java source code. Not even reflection will allow you to create new variables on the fly in an existing class.
Java is designed as a static programming language, and it works best if you use it that way.
(In theory, if you mess around with source code or byte code generation technologies, you can dynamically create a new class with new variables. However, this involves a HUGE amount of work, and not something that a sensible programmer contemplate doing to solve a simple problem. Besides, I doubt that this approach would actually help in your particular case.)
Upvotes: 1
Reputation: 74760
You want to use a Map with string keys, for example a HashMap<String, something>
.
Your example would look like this:
Map<String, Boolean> map = new HashMap<String, Boolean>();
map.put("bubby4j_falling", true);
if(map.get("bubby4j_falling")) {
...
}
Actually, in your case a Set<String>
would be more useful:
Set<String> fallingUsers = new HashSet<String>();
fallingUsers.add("bubby4j");
if(fallingUsers.contains("bubby4j")) { ... }
But uf you already have User
objects (and you should), you should better use a Set<User>
, or even let this falling
simply be a property of the user object. Then you could have a Map<String, User>
to get the user objects by name.
Upvotes: 7