Consistency of contains method on a HashSet and HashMap

我们两清 提交于 2019-12-11 17:49:38

问题


Why does containsAll method on a HashSet does not remain consistent if remove is called on the Set whereas a containsValue method on a HashMap remains consistent after a value is removed After a value is removed from a HashSet containsAll returns false even if all values were present where as in case of HashMap the containsValue method returns correct value

public static void main(String[] args)
    {

    HashSet<String> lookup=new HashSet<String>();
    HashMap<Integer,String> findup=new HashMap<Integer,String>();

    String[] Alltokens={"This","is","a","programming","test","This","is","a","any","language"};
    for(String s:Alltokens)
        lookup.add(s);

    String[] tokens={"This","is","a"};
    Collection<String> tok=Arrays.asList(tokens);

    lookup.remove(Alltokens[5]); 
     if(lookup.containsAll(tok))
       System.out.print("found");
    else    
        System.out.print("NOT found");

    Integer i=0;
    for(String s:Alltokens)
        findup.put(i++,s);
    boolean found=true;
    findup.remove(Alltokens[0]);
        findup.remove(5);               //Edit : trying to remove value whose key is 5
    for(String s:tokens)
        if(!findup.containsValue(s))
            found=false;
    System.out.print("\nIn map " + found);
}

Output NOT found In map true

Is there a way to keep containsAll consistent if remove method is called on the HashSet? Also if a value that was not present in the set is passed to remove method.ContainsAll remains consistent

        lookup.remove("Alltokens[5]");
    if(lookup.containsAll(tok))

//This will be true now where as it is false if a value already present is removed

May be it has got to do something with keys in HashMaps and no keys in HashSet.Can you please explain how do they work?


回答1:


Map.remove(Object) removes a mapping based on the key.

Since you use Integer objects as the keys (put(i++, s)) you will remove nothing when you call findup.remove(Alltokens[0])! Check its return value to see that it will return false.



来源:https://stackoverflow.com/questions/13339973/consistency-of-contains-method-on-a-hashset-and-hashmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!