i’m a newbie to java..i’m having difficulty in understanding generics. with what i understood i wrote the following demo program to understand Generics but there are errors..help required.
class GenDemoClass <I,S>
{
private S info;
public GenDemoClass(S str)
{
info = str;
}
public void displaySolidRect(I length,I width)
{
I tempLength = length;
System.out.println();
while(length > 0)
{
System.out.print(" ");
for(int i = 0 ; i < width; i++)
{
System.out.print("*");
}
System.out.println();
length--;
}
info = "A Rectangle of Length = " + tempLength.toString() + " and Width = " + width.toString() + " was drawn;";
}
public void displayInfo()
{
System.out.println(info);
}
}
public class GenDemo
{
public static void main(String Ar[])
{
GenDemoClass<Integer,String> GDC = new GenDemoClass<Integer,String>("Initailize");
GDC.displaySolidRect(20,30);
GDC.displayInfo();
}
}
if i replace type variables I and S with Integer and String in the GenDemoClass then code seems to work..
the errors are
error: bad operand types for binary operator '>'
while(length > 0)
^
first type: I
second type: int
where I is a type-variable:
I extends Object declared in class GenDemoClass
The problem is that most objects do not work with the > operator.
If you declare that your type
Imust be a subtype ofNumber, then you can convert the instance of type I to an int primitive in the comparison. For instanceAt this point you’re sunk because you cannot modify the
lengthvalue like you want to – it’s immutable. You can use a plain int for this purpose.In my opinion this is not an appropriate use of generics, as you don’t gain anything over using the primitive integer type.