我有一個巨大的浮點數組,我必須從中刪除重複項。我試圖創建一個HashTable來填充唯一值並將其傳遞迴另一個數組並將其返回。問題在於containsValue方法,它始終返回false,因此所有點都添加到HashTable中。HashTable containsValue無法正常工作
private float[] removeDuplicates1(float[] input){
Hashtable<Integer, float[]> h= new Hashtable<>();
for(int i=0; i<input.length/3; ++i) {
float[] pt= new float[]{input[i * 3], input[i * 3 + 1], input[i * 3 + 2]};
Log.i(TAG, Float.toString(pt[0]) + " " +Float.toString(pt[1]) + " " +Float.toString(pt[2])); //ok
Log.i(TAG, Boolean.toString(h.containsValue(pt))); //always false !?
if(!(h.containsValue(pt))){
h.put(i,pt);
Log.i(TAG, "added");
}
else Log.i(TAG, "NOT added");
}
float[] whitelist = new float[h.size()*3];
int a=0;
for(int j=0; j<h.size(); j++){
float[] f= h.get(j);
whitelist[a]= f[0];
whitelist[a+1]= f[1];
whitelist[a+2]= f[2];
a=a+3;
}
return whitelist;
}
我真的很感謝你的幫助。
你問一個陣列是否等於另一個,基本上是這樣。那是*永遠不會變成真 - 數組不會覆蓋'equals'。它看起來像你的輸入實際上是一個三元組的集合 - 聽起來你應該用三個「float」字段構造一個類(我們不能真正說出它們的含義),它恰當地覆蓋了'equals'。還要注意''Hashtable.containsValue'基本上是一個O(n)查找 - 這是一個非常糟糕的選擇去重複數據。 –
containsValue使用equals方法進行比較,兩個數組永遠不會相等。 –
不要忘記重寫'hashCode()',因爲你想使用一個HashTable,它只會比較具有相同哈希碼的對象。在你的情況下,最簡單的hashCode就是arry的長度。 – ctst