| Author |
Help me please with Generics..
|
Sandeep Awasthi
Ranch Hand
Joined: Oct 23, 2003
Posts: 597
|
|
1) class Fruit { } class Apple extends Fruit { } class Orange extends Fruit { } [b] if this works [b] ArrayList<Fruit> f = new ArrayList<Fruit>(); f.add(new Apple()); [b] why not [b] ArrayList<Number> a = new ArrayList<Number>(); a.add(new Integer("3")); [b] doesnt compile when Intger is subclass of Number[b] 2) public <T extends Integer> T add(T a,T b) { Integer res = a+ b; return res; } [b] why doesnt this compile? [b] Please help me
|
Sandeep
|
 |
Keith Lynn
Ranch Hand
Joined: Feb 07, 2005
Posts: 2341
|
|
Originally posted by Rajesh Thakare: 1) class Fruit { } class Apple extends Fruit { } class Orange extends Fruit { } if this works ArrayList<Fruit> f = new ArrayList<Fruit>(); f.add(new Apple()); why not ArrayList<Number> a = new ArrayList<Number>(); a.add(new Integer("3")); [b] doesnt compile when Intger is subclass of Number[b]
This compiled fine for me.
2) public <T extends Integer> T add(T a,T b) { Integer res = a+ b; return res; } why doesnt this compile? Please help me
Note that your type variable is Integer or anything that extends Integer(of course we know that a class can't extend Integer, but in the general case this is what it means). So T could be any subclass. Inside the method, you are creating an Integer object and trying to return it. However, this won't work, because the compiler has no idea what the actual type of T will be, and it's not legal to make the assignment of the superclass Integer(res is an Integer) to the return reference type (T is any subclass of Integer). [ October 14, 2006: Message edited by: Keith Lynn ]
|
 |
Sandeep Awasthi
Ranch Hand
Joined: Oct 23, 2003
Posts: 597
|
|
Hello Keith, Thank you very much for help.
|
 |
 |
|
|
subject: Help me please with Generics..
|
|
|