Unchecked warning with generics and compareTo

Hi,

I've worked on this quite a while, checking the forums and tutorials, but cannot seem to get the unchecked error to go away. I know I can use @SuppressWarning, but I'd like to avoid that. Is there a way to declare my "data" member as a non-raw Comparable type?

publicclass DataItem<T>implements Comparable<DataItem><?extends T>>{

private T data;

public DataItem( T data ){

this.data = data;

}

public T getData(){

return data;

}

publicint compareTo(DataItem<?extends T> o){

if ( datainstanceof Comparable )

return ((Comparable)data).compareTo( o.getData() );

else

return data.toString().compareTo( o.getData().toString() );

}

}

Error is as follows:

"c:\Program Files\Java\jdk1.6.0\bin\javac" -Xlint:unchecked DataItem.java

DataItem.java:14: warning: [unchecked] unchecked call to compareTo(T) as a member of the raw type java.lang.Comparable

return ((Comparable)data).compareTo( o.getData() );

^

1 warning

Thanks,

Dave

[1848 byte] By [dave_neddea] at [2007-11-27 1:14:15]
# 1

It's not an error, it's a warning. You are casting data, which is of whatever type T, to Comparable. You are casting to the raw type Comparable, and that's where the warning occurs. As the check for Comparable happens at runtime, you will have to live with some type-safety warning.

An option would be to require T to implement Comparable<T>, but that would restrict the kind of data your DataItem could take.

stefan.schulza at 2007-7-11 23:49:35 > top of Java-index,Core,Core APIs...
# 2
That's what I want to do - restrict my data to implement Comparable, but I couldn't figure out the Generics syntax.
dave_neddea at 2007-7-11 23:49:35 > top of Java-index,Core,Core APIs...
# 3

> That's what I want to do - restrict my data to

> implement Comparable, but I couldn't figure out the

> Generics syntax.

Are you looking for something like this?

public class DataItem<T extends Comparable ><T>> implements Comparable<DataItem><T>> {

private T data;

public DataItem( T data ) {

this.data = data;

}

public T getData() {

return data;

}

public int compareTo(DataItem<T> o) {

return data.compareTo( o.getData() );

}

}

fw@deneb.enyo.dea at 2007-7-11 23:49:35 > top of Java-index,Core,Core APIs...
# 4
Thanks, that's what I wanted. You make it look so easy :^).
dave_neddea at 2007-7-11 23:49:35 > top of Java-index,Core,Core APIs...
# 5
Now I understand your inital post's question about making data unraw, too. :)
stefan.schulza at 2007-7-11 23:49:35 > top of Java-index,Core,Core APIs...