Re: How to: referencing variables using the contents of otehr variables.
fguy64s@gmail.com wrote:
Is there a way to reference a variable using the contents of another
variable?
I have a variable, primitive data type char, that can contain many
different values. For each of these values, there is a corresponding
array of the same name as the contents of the char variable.
To do this precisely as you state in Java would be bad practice. Java really
doesn't have an 'eval' construct, although you can use reflection to get at
stuff in more or less that way. To do so, however, is messy, unsafe and
rather unmaintainable.
For example, the char variable named P can have the value 'K', and
there is also a two dimensional array named K[][] of type String.
Arrays and other objects don't have names. Variables have names, and their
contents point to objects or are primitive values.
I want to be able to access the array directly, without using a switch
(P) and explicitly having a case for each possible value of P.
Mark Space wrote:
Yes and no. First, you can't have two variables declared in the same
scope with the same name;
char k;
int[][] k; // error
won't compile. You must give them different names.
The easiest way to accomplish what you want is probably to just make
your own type.
class CharData {
char k;
int[][] data;
public CharData( char c, int [][] d )
{
this.k = c;
this.data = d;
}
public int [][] getData()
{
return this.data;
}
}
Now you have bound a char and a two dimensional array 'data' together.
You don't need a switch or any look up to access one from the other.
<http://java.sun.com/javase/6/docs/api/java/util/Map.html>
Map <Character, CharData> lookup =
new HashMap <Character, CharData> ();
....
lookup.put( 'k', new CharData( 'k', new int [3][] ));
....
int [][] found = lookup.get( 'k' ).getData();
....
and so on.
--
Lew