Why aren't Java Collections remove methods generic?

前端 未结 10 2154
旧巷少年郎
旧巷少年郎 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:49

    It was a compromise. Both approaches have their advantage:

    • remove(Object o)
      • is more flexible. For example it allows to iterate through a list of numbers and remove them from a list of longs.
      • code that uses this flexibility can be more easily generified
    • remove(E e) brings more type safety to what most programs want to do by detecting subtle bugs at compile time, like mistakenly trying to remove an integer from a list of shorts.

    Backwards compatibility was always a major goal when evolving the Java API, therefore remove(Object o) was chosen because it made generifying existing code easier. If backwards compatibility had NOT been an issue, I'm guessing the designers would have chosen remove(E e).

提交回复
热议问题