Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics usage difficulty

Tags:

java

generics

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
like image 886
Koushik Shetty Avatar asked Feb 13 '26 20:02

Koushik Shetty


1 Answers

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.

like image 74
I82Much Avatar answered Feb 15 '26 09:02

I82Much



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!