嗯,你可以使用地图的地图。
Map<String, Map<String, Boolean>> map = new HashMap<String, Map<String, Boolean>>();
但我会将这张地图隐藏在一个类后面,因为初始化并非易事。您还必须创建内部地图。
你终于可以像这样使用它了
String var1 = "1", var2 = "2"
if (map.get(var1).get(var2))
{
/* Without proper initialization map.get(var1) could be null,
* so it's important that you create the innermap up on first use of 'var1':
* map.put(var1, new HashMap<String, Boolean>());
*
* and to associate var1 and var2 with a boolean value:
* map.get(var1).put(var2, true);
*/
}
甚至更好
MapHider instance = new MapHider();
if (instance.check(var1, var2))
{
}
这是一个通用的方法和使用示例
/**
* AssociativeArray2D - Two dimensional associative array
*
* NOTE: Not thread-safe.
*
* @param <K1> type of first key
* @param <K2> type of second key
* @param <V> type of value
*/
public class AssociativeArray2D<K1, K2, V> {
/* standard value if no value is in the map */
private final V standard;
private Map<K1, Map<K2, V>> map = new HashMap<K1, Map<K2, V>>();
public AssociativeArray2D(V standard) {
this.standard = standard;
}
public static AssociativeArray2D<String, String, Boolean> getSSB() {
return new AssociativeArray2D<String, String, Boolean>(false);
}
public void add(K1 first, K2 second, V value) {
Map<K2, V> m = map.get(first);
if (m == null) {
m = new HashMap<K2, V>();
map.put(first, m);
}
m.put(second, value);
}
public V check(K1 first, K2 second) {
Map<K2, V> m = map.get(first);
if (m == null) {
m = new HashMap<K2, V>();
map.put(first, m);
m.put(second, standard);
}
return m.get(second);
}
public static void main(String[] args) {
AssociativeArray2D<String, String, Boolean> a = AssociativeArray2D.getSSB();
if (a.check("1", "2")) {
System.out.println("This, won't print!");
}
a.add("1", "2", true);
if (a.check("1", "2")) {
System.out.println("This, will print!");
}
}
}
输出
这,将打印!