如果你能满足以下条件:
- 您知道代码生成时的所有密钥。
- 您知道代码生成时的所有值(方法)。
你可以使用这样的代码:
public class Table {
public static int hash(String key) {
/* you can use any type of key and whatever hash function is
* appropriate; this just meant as a simple example.
*/
return key.length();
}
public static Integer find(String s, int value) {
int h = hash(s);
switch (h) {
case 4: // "zero"
if (s.equals("zero"))
return methodZero(value);
case 6: // "triple"
if (s.equals("triple"))
return methodTriple(value);
case 11: // "squarePlus3"
if (s.equals("squarePlus3"))
return methodSquarePlus3(value);
default:
throw new UnsupportedOperationException(s);
}
}
private static Integer methodZero(int value) { return 0; };
private static Integer methodTriple(int value) { return value * 3; };
private static Integer methodSquarePlus3(int value) { return value * value + 3; };
/**
* Just a demo.
*/
public static void main(String arguments[]) {
System.out.println("Zero(5): " + find("zero", 5));
System.out.println("Triple(5): " + find("triple", 5));
System.out.println("SquarePlus3(5): " + find("squarePlus3", 5));
System.out.println("boom!");
find("missingcode", 5);
}
}
如果您需要放松任何一个要求,我不相信您可以静态地做所有事情。
如果您希望能够添加新键,则必须在添加时创建一个普通的哈希表来存储它们。(您可以在default
代码中检查它。)
如果您希望能够替换值,则必须在此处使用间接级别,可能使用Method
对象或实现Callable
(您可以从方法体中调用它们methodZero
)。