[英]Comparing values using hashtable
有一个像这样的表:
Code(starts with) Value
1 AAA
101D BBB
101DG CCC
2 DDD
上表包含列代码和相应的值。 Code列表示字符串以给定的代码开头,并将其与用户的输入代码进行比较,将从表的value列中分配相应的值。
例如:
我将下表放在键为代码列而值作为值列的哈希表中。
HashTable hash= new HashTable();
hash.put("1","AAA");
hash.put("101D","BBB");
hash.put("101DG","CCC");
hash.put("2","DDD");
String comp="101D1111";//string to compare
Iterator itr= hash.entrySet().iterator();
while(itr.hasNext())
{
Map.Entry e=(Map.Entry)itr.next();
String key= (String).getKey();
//**Here logic is needed to compare comp and key and retrieve the corrsponding value here as BBB**
}
请帮我这个逻辑。
您必须首先按密钥长度对条目进行排序,最长的条目在前,最短的条目在后。 因为你首先要检查你的代码是否与启动101DG
,然后才检查它是否符合启动101DG
最后1
。
然后要检查匹配项,您可以使用以下方法:
if (comp.substring(0,key.length()).equals(key)) {
// it's a match — use this Value
}
我认为HashTable
并不是用于此目的的良好数据结构,因为如果您要遍历所有条目,那么拥有HashTable
何在?
更好的结构(尽管要执行更多的工作)是一棵树。 树的每个节点将代表一个前缀以及与之关联的值:
例如,这是您的示例树的外观:
ROOT
/ \
1 (AAA) 2 (DDD)
|
10
|
101
/
101D (BBB)
|
101DG (CCC)
现在,对于给定的用户代码,您每次都在拥有该用户代码下一个字符的子节点之后,从ROOT开始遍历该树。 当找不到任何匹配的子节点时,您将停止。 您访问的每个节点都采用存储在其中的值。 您返回找到的最后一个值。
如果您仍然不熟悉复杂的数据结构,那么这个简单的解决方案将为您提供帮助
String keySearch=new String();
String val=null;
for(i=0;i<comp.length();i++){
keySearch+=comp.charAt(i);
if(table.contains(keySearch)){
val=map.get(keySearch);
}
else
break;
}
但是在这种情况下使用HashTable并不是很有效
下面的代码可以解决问题。 您还可以在迭代器中使用泛型来确保代码类型安全。
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
public class TestClass {
public static void main(String[] args) {
HashMap hash= new HashMap<String, String>();
hash.put("1","AAA");
hash.put("101D","BBB");
hash.put("101DG","CCC");
hash.put("2","DDD");
String comp="101D1111";//string to compare
Iterator itr= hash.entrySet().iterator();
String value = null;
int length = 0;
while(itr.hasNext())
{
Map.Entry e=(Map.Entry)itr.next();
if(comp.startsWith(((String)e.getKey())) && ((String)e.getKey()).length() > length) {
value = (String)e.getValue();
length = ((String)e.getKey()).length();
}
//**Here logic is needed to compare comp and key and retrieve the corrsponding value here as BBB**
}
System.out.println(value);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.