[英]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.