我是 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();
}
}
如果我在 GenDemoClass
中用 Integer
和 String
替换类型变量 I 和 S,那么代码似乎可以工作。
错误是
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
最佳答案
问题是大多数对象不能使用 > 运算符。
如果您声明您的类型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
}
在我看来,这不是对泛型的适当使用,因为使用原始整数类型不会获得任何好处。
关于Java泛型使用难度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13392580/