aspose file tools
The moose likes Java in General and the fly likes Help me please with Generics.. Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Help me please with Generics.." Watch "Help me please with Generics.." New topic
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Help me please with Generics..
 
Similar Threads
Why the answer is... MasterExam
Why this is producing compile error
Generic question from Master Exam
Generics
Generics question from bonus exam