Why aren't Java Collections remove methods generic?

前端 未结 10 2128
旧巷少年郎
旧巷少年郎 2020-11-22 04:49

Why isn\'t Collection.remove(Object o) generic?

Seems like Collection could have boolean remove(E o);

Then, when you ac

10条回答
  •  不思量自难忘°
    2020-11-22 05:43

    Because it would break existing (pre-Java5) code. e.g.,

    Set stringSet = new HashSet();
    // do some stuff...
    Object o = "foobar";
    stringSet.remove(o);
    

    Now you might say the above code is wrong, but suppose that o came from a heterogeneous set of objects (i.e., it contained strings, number, objects, etc.). You want to remove all the matches, which was legal because remove would just ignore the non-strings because they were non-equal. But if you make it remove(String o), that no longer works.

提交回复
热议问题