I\'m trying to make a generic class that basically compares two object with para
ID: 3556819 • Letter: I
Question
I'm trying to make a generic class that basically compares two object with parameter, but couldnt make it work. Basically I want to be able to have a method compareto() that takes any same object type, ie String, int, long,...as both data are the same and compare them.
JAVA LANGUAGE
-----------------------------------------------------------------------------
class generic <E extends Comparable<E>>{
private E data1;
private E data2;
public void fun(E d1, E d2){
data1 = d1;
data2 = d2;
System.out.println(data1.compareTo(data2));
}
}
public class TestClass
{
public static <E> void main(String[] args){
generic<E> rbt = new generic();
rbt.fun("Hey","what");
}
}
ANY IDEAS why is it not working
thanks
Explanation / Answer
/***
While Defining your class, you have to make it Generic, (You have done it right), But while using it (in main method) you need to pass actual Specific Datatype (Like String, List etc..,) for it to work
**/
/** Please REVIEW and RATE **/
class generic<E extends Comparable<E>> {
private E data1;
private E data2;
public void fun(E d1, E d2) {
data1 = d1;
data2 = d2;
System.out.println(data1.compareTo(data2));
}
}
public class TestClass {
public static void main(String[] args) {
generic<String> rbt = new generic<String>();
rbt.fun("Hey", "what");
}
}