1

What is the difference between E and Object types, when referring to the following example?

Example

List interface has two methods, Add(E e) and Remove(Object obj).

How was it decided to use E or Object for each method?

Phrased another way, how would I know whether to use E or Object when writing the header of my own written method?

user2793223
  • 13
  • 1
  • 3
  • 3
    Do you know about generics? Have a look [here](http://docs.oracle.com/javase/tutorial/java/generics/) – Sotirios Delimanolis Sep 18 '13 at 21:28
  • 1
    This question is asked *a lot*. Look around a bit. – arshajii Sep 18 '13 at 21:29
  • 2
    When using a generic List, it makes sense to only allow adding `E`. However, you can try to remove anything, as `remove(Object obj)` relies on the `equals(Object other)` method. So, you should use `E` where it makes more sense, and `Object` where it makes more sense depending on your method. – jlordo Sep 18 '13 at 21:31

1 Answers1

0

The Collections Framework sticks firmly to the rule that if an arbitrary Object could corrupt the collection for future use, then E was used; otherwise Object was used.

For example, removing an Integer from a List<String> is a no-op, so it is allowed; adding an Integer to a List<String> would cause a ClassCastException in the future, so it is not permitted.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • Thanks for the answer. My professor previously answered something similar, but wasn't as detailed. And it was hard for me to Google/search here similar topics. – user2793223 Sep 20 '13 at 06:23