GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes New to Generics Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "New to Generics" Watch "New to Generics" New topic
Author

New to Generics

S Chan
Ranch Hand

Joined: Jul 25, 2011
Posts: 51
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: 18570
    
    8

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: 51
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: 51
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: 51
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: 39053
    
  23
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: 19697
    
  20

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 - OCEEJBD 6
How To Ask Questions How To Answer Questions
S Chan
Ranch Hand

Joined: Jul 25, 2011
Posts: 51
Ah! That rings the bell!

Thank you for the explanations and advices!
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39053
    
  23
Well done ... and you're welcome.
 
GeeCON Prague 2014
 
subject: New to Generics