2013-02-20 67 views
0

我有一個Hashset,我在其中存儲一個列表唯一的URL。我想將其作爲一個2-H Hashset,其中我有一個唯一的URL列表和一個非唯一的數字。然後我希望能夠在這個列表中搜索一個URL和與之關聯的數字。以下是我想要創建的列表的一個示例。Hashset 2d數組

www.test1.com - 200 
www.test2.com - 503 
www.test3.com - 400 
www.test4.com - 200 
www.test5.com - 404 
www.test6.com - 404 

然後我想要搜索www.test2.com並找回503.這是否可能與一個Hashset?或者我應該看看別的東西?

回答

3

哈希映射可能更適合您的情況。

Map<String, Integer> urlHashMap = new HashMap<String, Integer>(); 
urlHashMap.put("www.test1.com", 200); 
System.out.println(urlHashMap.get("www.test1.com")); //outputs 200 

它提供了一個更簡單,更簡單的方法從地圖獲取值。

+0

大家是正確的,它解決了我的問題,選擇你作爲正確答案爲你還演示瞭如何使用密鑰訪問該值。謝謝! – Peck3277 2013-02-20 14:07:35

+1

謝謝。我很高興能夠幫忙。 – Achrome 2013-02-20 14:08:27

3

嘗試使用HashMap,其中URL是鍵,返回碼是值。 HashMap在幕後使用HashSet。

2

看來你的合適的數據結構似乎是構建一個Dictionary \ HashMap(所有的鍵都是唯一的:test1,test2,...,而且值不一定是唯一的)。

例如:

HashMap<String,String> pairs = new HashMap<String,String>(); 

pairs.put("www.test1.com","404"); 
2

你可以達到你想要的地圖,而不是什麼,具體如下:

Map<String, Integer> map = new HashMap<String, Integer>(); 
map.put("www.test1.com", 200); 
map.put("www.test2.com", 503); 
...and so on