(Raymond Martineau) writes:
> In C, it's possible to create an array of the following data structure to
> associate a function call with a specific key or identifier:
>
> struct {
> char *key;
> void (*function)();
> } a[] = { { "Function1", Function1} ,
> { "Function2", Function2}};
>
> (Or some other varient that you are comfortable with.)
>
> I would like to know the appropriate procedure on how to implement the same
> in Java. I would prefer to use the above system, as it can be much quicker
> to call a function by looking up the associated token in a hashtable as
> opposed to writing many lines of an if/else ladder.
public interface Fun {
void call();
}
public Pair {
public final String key;
public final Fun fun;
public Fun(String key, Fun fun) {
this.key = key; this.fun = fun;
}
}
Pair[] a =
{ new Pair("Function1",
new Fun() {
public void call() { ... body of Function1 ... }
}),
new Pair("Function2",
new Fun() {
public void call() { ... body of Function2 ... }
}),
...
}
If you build a hash map the array like this:
Map<String,Fun> action = new HashMap<String,Fun>();
for (Pair p : a)
action.put(p.key, p.fun);
you get very fast execution of each instruction:
action.get(keyword).invoke();
Peter