![](/img/trans.png)
[英]How to remove the dulpicates from ArrayList<HashMap<String,Object>> in java?
[英]Remove an Object from an arraylist in a hashmap
我需要你的幫助,我創建了這兩個類
public class Arch <N,T>{
T label;
N start;
N end;
...constructor...
public class Graph <N,T>{
private ArrayList<N> nodes;
private HashMap<N,ArrayList<T>> arch; //for each Node I have saved an arrayList of Archs
//connected to him
private int nNode;
private int nArch;
private boolean oriented;
...constructor..
我需要 Graph 中的一種方法來從 hashmap 中的 ArrayList 中刪除 Arch。
我在 class 圖表中這樣嘗試:
public void deleteArch(N start, N end){
ArrayList<Arch<N,T>> archsForNode=(ArrayList<Arch<N,T>>)arch.get(start);
for(Arch<N,T> a : archsForNode){
if(a.start==start || a.end == end) {
archsForNode.remove(a);
}
}
}
但是當我在我的測試主體中對其進行測試時,結果是 hashmap 中的 ArrayList 沒有任何變化。
請有人可以幫助我!
謝謝你們
我 90% 確定您的問題的根本原因是您的類沒有覆蓋Object#equals(Object)
和Object#hashCode()
方法。 In order for a remove()
function to work, it needs to compare the object being passed to the function against members of the collection you are iterating over so that the object that's equal to the argument is removed.
我建議您研究覆蓋這些方法以正確實施。 但是,總而言之,您的類必須實現這些方法,並且在復雜類(包含其他 object 引用的類)的情況下,這些類中的每一個都必須覆蓋這些方法。 像String
這樣的類在這些情況下起作用的原因是String
class 覆蓋了這些方法。 對於您的自定義類,您必須這樣做。 從邏輯上思考這個問題。 如果代碼無法確定哪些對象與您要查找的對象相等,那么集合如何神奇地刪除和 object?
我懷疑deleteArch
會拋出ConcurrentModificationException
,因為您在迭代它時正在修改archsForNode
:
for(Arch<N,T> a : archsForNode){
if(a.start==start || a.end == end) {
archsForNode.remove(a);
}
}
這是不允許的。
有關更多信息,請參閱此問答。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.