Results 1 to 3 of 3
  1. #1
    ajeeb is offline Member
    Join Date
    Dec 2008
    Rep Power

    Default Generics and Wildcards

    Am trying to understand wildcards (bounded) in java generics. I have method say:

    Java Code:
    	public static void someMethod(List <? extends Number> list) {
    		list.add(0, new Integer(9)); //compile error
    While trying to add to the list (a list of "anything that extends the Number class" ), i will get a compile-time error. Why the compiler does not understand that Integer is a sub-type of Number ? Am I missing some important point ?

  2. #2
    emceenugget is offline Senior Member
    Join Date
    Sep 2008
    Rep Power


    Found this interesting, since I haven't worked with generics in quite some time, and did a little search. Basically, it's not safe to add an Integer to a list of objects that extend Number because we do not know what ? is. That is, ? is a subtype of Number, but we do not know if it is Rectangle or a supertype of Rectangle.

    More info can be found in pages 6-7 in this pdf file:

    Anyways, you should just use List<Number>, as all classes that extend Number can be put into the list anyways.

  3. #3
    Steve11235's Avatar
    Steve11235 is offline Senior Member
    Join Date
    Dec 2008
    Rep Power


    Emcee is right about not complicating the type designation. In fact, it is the cause of your compile error.

Similar Threads

  1. Generics in java
    By ajeeb in forum Advanced Java
    Replies: 5
    Last Post: 01-23-2009, 04:56 PM
  2. generics
    By tascoa in forum Forum Lobby
    Replies: 2
    Last Post: 10-09-2008, 07:58 PM
  3. Help w/ generics
    By Hollywood in forum New To Java
    Replies: 2
    Last Post: 02-16-2008, 03:08 AM
  4. Generics
    By sireesha in forum New To Java
    Replies: 2
    Last Post: 01-10-2008, 11:08 PM
  5. Generics
    By eva in forum New To Java
    Replies: 2
    Last Post: 01-04-2008, 09:10 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts