我是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 代码中用Integer
and替换类型变量 I 和 S似乎可以工作..错误是String
GenDemoClass
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