What is the time and space complexity of method retainAll when used on HashSets in Java?

后端 未结 2 1706
挽巷
挽巷 2020-12-06 10:17

For example in the code below:

public int commonTwo(String[] a, String[] b)
{
    Set common = new HashSet(Arrays.asList(a));
    common.retain         


        
2条回答
  •  死守一世寂寞
    2020-12-06 10:49

    The implementation can be found in the java.util.AbstractCollection class. The way it is implemented looks like this:

    public boolean retainAll(Collection c) {
            Objects.requireNonNull(c);
            boolean modified = false;
            Iterator it = iterator();
            while (it.hasNext()) {
                if (!c.contains(it.next())) {
                    it.remove();
                    modified = true;
                }
            }
            return modified;
        }
    

    So it will iterate everything in your common set and check if the collection that was passed as a parameter contains this element.

    In your case both are HashSets, thus it will be O(n), as contains should be O(1) amortized and iterating over your common set is O(n).

    One improvement you can make, is simply not copy a into a new HashSet, because it will be iterated anyway you can keep a list.

提交回复
热议问题