Why does List.add(E) return boolean while List.Add(int, E) returns void?

后端 未结 3 1671
失恋的感觉
失恋的感觉 2020-12-18 19:53

Looking at the javadoc I saw the that an ArrayList has an overloaded add method:

public boolean add(E e)

Appends the specified element to

3条回答
  •  执念已碎
    2020-12-18 19:58

    Because it's an extra information which doesn't cost anything and can be useful in certain situations. For example:

    Set set = new HashSet();
    set.add("foobar");
    boolean wasAlreadyThere = set.add("foobar");
    

    Otherwise you would have to do

    boolean wasAlreadyThere = set.contains("foobar");
    set.add("foobar");
    

    which requires twice the work (first you have to lookup, then lookup again to add).

提交回复
热议问题