2012-11-15 84 views
3

我是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然後代碼似乎工作.. IntegerString 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 
+1

你不能比較數字和''我可以幾乎任何東西。考慮如果你聲明'GenDemoClass ' –

+0

是的,我會考慮那會發生什麼,但我正在嘗試一個演示..我假設只傳遞整數..所以根據我的想法,我是一個Integer的佔位符,因此進一步與編碼..如果這將工作,那麼我的假設是正確的..謝謝你的答覆.. –

+0

如果你已經解決了這個問題,你可能想接受@ michael答案。 –

回答

2

的問題是,大多數對象不與>操作工作前檢查instanceof

如果您聲明您的類型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 
     } 

在我看來,這不是一個適當的泛型使用,因爲你沒有獲得任何優勢,使用原始整數類型。

+0

感謝您的迴應..是啊,這只是一個演示程序瞭解泛型,所以沒有注意到程序的用處。我也遇到了第二種類型的問題,也就是當我通過字符串類型時...我應該擴展第二類字符串類? –

+0

當然你可以說S延伸字符串。但真的爲什麼在這種情況下甚至使用通用的S? – I82Much

1

會發生什麼,如果你傳遞的東西是不是一個整數到I length文件?現在你不是說它應該是任何特定的類型,所以如果你要傳入一個字符串,這條線會發生什麼?

while(length > 0) 

你假設length這裏是一個整數,當你很清楚一般將它定義爲一個I

+0

是的,這個想法在我開始時就開始思考,但我更多地參與解決其他問題第一..感謝 –

0

> op對任意類別I無效。

1

你應該使用

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

} 
+0

肯定會做..感謝您的迴應 –