3

我是java的新手..我很难理解泛型。据我了解,我编写了以下演示程序来理解泛型,但有错误..需要帮助。

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();
    }
}

如果我在then 代码中用Integerand替换类型变量 I 和 S似乎可以工作..错误是StringGenDemoClass

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
4

4 回答 4

2

问题是大多数对象不能与 > 运算符一起使用。

如果您声明您的类型I必须是 的子类型Number,那么您可以在比较中将类型 I 的实例转换为 int 基元。例如

class GenDemoClass <I extends Number,S> 
{


public void displaySolidRect(I length,I width)
    {
        I tempLength = length;
        System.out.println();
        while(length.intValue() > 0)
        {

        }

在这一点上,你已经沉没了,因为你不能length像你想要的那样修改值——它是不可变的。为此,您可以使用普通的 int。

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
        }

在我看来,这不是对泛型的适当使用,因为您不会比使用原始整数类型获得任何好处。

于 2012-11-15T06:42:09.873 回答
1

如果您将不是整数的东西传递到I length文件中会发生什么?现在你不是说它应该是任何特定的类型,所以如果你要传入,比如说,一个字符串,这行会发生什么?

while(length > 0)

在这里你假设length是一个整数,当你非常清楚地将它一般地定义为I.

于 2012-11-15T06:38:51.880 回答
1

你应该instanceof在使用前检查

if (I instanceof Integer){ 
   // code goes here

}
于 2012-11-15T06:41:05.557 回答
0

>操作对任意类无效I

于 2012-11-15T06:40:00.227 回答