1

Are these two code snippets are totally same? Is there any difference?

public static void printList(List<?> list) {
for (Object elem: list)
    System.out.print(elem + " ");
}


public static void printList(List list) {
for (Object elem: list)
    System.out.print(elem + " ");
}
user2693979
  • 2,482
  • 4
  • 24
  • 23
  • 5
    The only difference is that in method receiving `List>` you cannot add elements in the list while the other method allows it. – Luiggi Mendoza Jan 04 '14 at 14:09
  • 1
    @LuiggiMendoza Nothing stopping you from adding items to `List>`. It's just using generics, while the other list isn't. – t0mppa Jan 04 '14 at 14:11
  • 1
    @t0m You'll want to test that. – Sotirios Delimanolis Jan 04 '14 at 14:12
  • 1
    @t0mppa I recommend you to test it in code – Luiggi Mendoza Jan 04 '14 at 14:14
  • 1
    @t0mppa "Nothing stopping you from adding items to `List>.`" nothing beside compiler, who doesn't know type of elements in the list so just to be safe prevents you from adding anything to list (except `null`). You can add elements to this list, but not via `List>` reference (you can try casting it to `List` for example). – Pshemo Jan 04 '14 at 14:15
  • You can check the link http://stackoverflow.com/questions/6231973/difference-between-list-list-listt-liste-and-listobject. It addresses your question clearly. – Pradeep Kr Kaushal Jan 04 '14 at 14:15
  • It's not only about not being able to add to the List, it's about not being able to use any method that uses the generic type variable as a parameter with anything other than null. – Sotirios Delimanolis Jan 04 '14 at 14:16
  • perhaps you'll find this explanation a bit easier http://stackoverflow.com/questions/2575363/generics-list-extends-animal-is-same-as-listanimal?rq=1 – Hernán Erasmo Jan 04 '14 at 14:17
  • 1
    @SotiriosDelimanolis & @LuiggiMenodza: Ah, you learn something new every day. Never used a `List>`, so mistakenly thought it works the same. Thanks for pointing that out. – t0mppa Jan 04 '14 at 14:19
  • See http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedTypes.html#FAQ303 – Jon Skeet Jan 04 '14 at 14:20
  • @SotiriosDelimanolis You are right, adding was just example. It could be also removing, setting or any other method using generic type. I just needed one of many scenarios that could show why it is not possible. – Pshemo Jan 04 '14 at 14:22

0 Answers0