我是java..i'm的新手,很難理解泛型。與我的理解我寫了下面的演示程序來了解泛型,但有錯誤..幫助需要。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
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
你不能比較數字和''我可以幾乎任何東西。考慮如果你聲明'GenDemoClass' –
是的,我會考慮那會發生什麼,但我正在嘗試一個演示..我假設只傳遞整數..所以根據我的想法,我是一個Integer的佔位符,因此進一步與編碼..如果這將工作,那麼我的假設是正確的..謝謝你的答覆.. –
如果你已經解決了這個問題,你可能想接受@ michael答案。 –