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 I must be a subtype of Number, then you can convert the instance of type I to an int primitive in the comparison. For instance
class GenDemoClass <I extends Number,S>
{
public void displaySolidRect(I length,I width)
{
I tempLength = length;
System.out.println();
while(length.intValue() > 0)
{
}
At this point you're sunk because you cannot modify the length value like you want to - it's immutable. You can use a plain int for this purpose.
public void displaySolidRect(I length,I width)
{
int intLength = length.intValue();
int intHeight = width.intValue();
System.out.println();
while(intLength > 0)
{
// iterate as you normally would, decrementing the int primitives
}
In my opinion this is not an appropriate use of generics, as you don't gain anything over using the primitive integer type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With