从头开始的恒定时间查找
如果您正在寻找一个在恒定时间内检索与键关联的值的 Map(这意味着不必查看大多数值),那么您将无法做得更快,因为需要处理数组。
但是,您可以使用已经以这种方式编写的实用程序:com.google.common.collect.Maps.uniqueIndex
瞬时转换,线性时间查找
如果您对每次都在数组中搜索键的 Map 感到满意,那么您可以通过定义一个实现 Map 接口的新类来立即使用您的两个数组创建 Map:
class TwoArrayMap implements Map<String, String> {
private final String[] keys;
private final String[] values;
// If you want to enable to add more key value pairs to your map, and
// want to make the process faster, you could use ArrayLists instead of arrays
public TwoArrayMap(String[] array1, String[] array2){
if(array1 == null || array2 == null || array2.length < array1.length)
throw new IllegalArgumentException();
keys = array1;
values = array2;
// Alternatively, you could want to clone the arrays, to
// make sure they are not modified, using array1.clone(), etc
}
public String get(String key){
for(int i=0; i<keys.length; i++)
if(key == null && key == null || key != null && key.equals(k) )
return values[i];
return null;
}
public String put(String key, String Value) throws OperationNotSupportedException {
throw new OperationNotSupportedException();
// alternatively, you could resize the arrays and add a new key, or use an ArrayList
}
}
Map<String, String> myMap = new TwoArrayMap(keys, values);
惰性转换,转换后恒定时间查找
另一种方法是“懒惰”地进行,即修改上述类,使其在内部保留对 HashMap 的引用,并仅在查找元素时填充它:
class TwoArrayMap implements Map<String, String> {
private final Map<String, String> hashmap;
private int maxIndexAlreadyTransferred = -1;
private final String[] keys;
private final String[] values;
public TwoArrayMap(String[] array1, String[] array2){
if(array1 == null || array2 == null || array2.length < array1.length)
throw new IllegalArgumentException();
hashmap = new HashMap<>();
keys = array1;
values = array2;
// Alternatively, you could want to clone the arrays, to
// make sure they are not modified, using array1.clone(), etc
}
public String get(String key){
if(hashmap.containsKey(key))
return hashmap.get(key);
String k, value;
while( maxIndexAlreadyTransferred + 1 < keys.length ){
k = keys[ maxIndexAlreadyTransferred + 1 ];
value = values[ maxIndexAlreadyTransferred +1 ];
if(!hashmap.containsKey(k))
hashmap.put( k, value );
maxIndexAlreadyTransferred++;
if(key == null && k == null || key != null && key.equals(k) )
return value;
}
return null;
}
public String put(String key, String Value) {
hashmap.put(key, value);
}
}
这个解决方案意味着:
- 即时创建新对象
- 第一次查询时的线性时间查找,直到所有内容都传输完毕
- 之后的恒定时间查找,表现为哈希表