| Author |
New to Generics
|
S Chan
Ranch Hand
Joined: Jul 25, 2011
Posts: 50
|
|
Hi all I am new to Generics but I want to try it out building a class that uses generics. I am stuck at something so I hope someone would give me a hand. Thank you.
Basically, I want the supported type to be a solid class of interface java.lang.Comparable, so I thought may be this would work:
Then later on, in one of my defined methods, I want the argument to run a method which is defined in the Comparable:
Eclipse complains about the type is not applicable for the arguments (E)
I wonder what is wrong here.
|
 |
Paul Clapham
Bartender
Joined: Oct 14, 2005
Posts: 16483
|
|
You know perfectly well what type is going to be passed to the Comparable. So don't put ? there. This is what you want:
|
 |
S Chan
Ranch Hand
Joined: Jul 25, 2011
Posts: 50
|
|
I see. That solves the problem. Thank you for your help!
Actually before I had ? , I was trying with ? extends E and ? super E .
I had read the documents but didn't quite understand what they are and when to use them.
Can someone be kind and explains them to me in plain English?
|
 |
S Chan
Ranch Hand
Joined: Jul 25, 2011
Posts: 50
|
|
I find it very confusing because I don't know when to use ? and when to use E.
Let's take an example, I have the following:
I know I shouldn't use new ArrayList<?>() here but how can I make sure clones is a list of ? type (defined by the argument)?
Also, even thought I have for the class declaration, why can't I have in the containsAll method?
|
 |
S Chan
Ranch Hand
Joined: Jul 25, 2011
Posts: 50
|
|
Would this be a better way of re-writing containsAll?
Need some expert advice here. I am so bad at this... sigh...
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32712
|
|
Since the E class might not implement Comparable, but might extend a class which implements Comparable, the actual type parameter should be
<E extends Comparable<? super E>>
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
|
Campbell is right. Without the ? super part you wouldn't be able to use java.sql.Timestamp for instance, as it extends java.util.Date and therefore implements Comparable<java.util.Date> - not Comparable<java.sql.Timestamp>.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
S Chan
Ranch Hand
Joined: Jul 25, 2011
Posts: 50
|
|
Ah! That rings the bell!
Thank you for the explanations and advices!
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32712
|
|
Well done ... and you're welcome.
|
 |
 |
|
|
subject: New to Generics
|
|
|