2017-05-29 36 views
-1

我使用HashSet<String>存儲值,但一些字符串的碰撞具有相同的散列碼。 HashSet如何處理碰撞。的Java HashSet的<String>對象

List<ClassA> getValuesFromA(){ 

} 

List<ClassA> getValuesFromB(){ 

} 

Set <String> a = new HashSet<String>(getValuesFromA()); // data overwritten due to hash code collision 

Set <String> b = new HashSet<String>(getValuesFromB()); // data overwritten due to hash code collision 

a.removeAll(b); 
a.stream().forEach(t -> t.setSomeValue(X)); 
b.addAll(a); 

我使用HashSet在O(1)中爲每個元素然後b +(a - b)查找減號b。但是,在HashSet中存儲數據時,一些數據被覆蓋。有沒有人有任何想法來執行此操作而不更改散列方法或數據結構?

+3

「不過,雖然在HashSet的存儲數據我失去了一些數據。」請更清楚一點。請注意,散列碼衝突*不會丟失數據 - 它們只是使其查找值的效率稍低。請提供[mcve],因爲您的問題目前尚不清楚。 –

+3

(你可能只是想用'retainAll',順便說一句。) –

+0

檢查了這一點:https://stackoverflow.com/questions/2851938/efficiently-finding-the-intersection-of-a-variable-number-of-臺套的串 –

回答

0

但是,儘管HashSet的存儲數據我失去了一些數據。如何 處理這個?

碰撞hashCode()結果不會丟失或覆蓋HashSet中具有相同哈希碼的對象。
具有相同散列碼的兩個對象可以存儲在相同的HashSet中。

在你的示例代碼,你這樣做:

Set <String> a = new HashSet<String>(getValuesFromA()); 

Set <String> b = new HashSet<String>(getValuesFromB()); 

a.removeAll(b); 

a刪除包含在b所有值。
所以a將包含a減B values
你做排除。

然後你做:

b.addAll(a); 

它不是一個路口爲您添加到ba值是包含在b

你還是使用retainAll()方法,通過喬恩斯基特的建議,這似乎以滿足您的要求:

僅保留此set中那些包含在 指定集合中的元素

Set<String> intersectionSet = new HashSet<>(getValuesFromA());  

intersectionSet.retainAll(getValuesFromB());