2012-10-11 19 views
0

很長一段時間,我一直在試圖讓一段代碼工作,而這是不可能的。我有類需要一個通用的,我已經設置爲整數。所以我嘗試了follwoing:嚴重的泛型問題:整數與整數java

public class a<T> //set generics for this function 
{ 
    private T A; 
    protected boolean d; 

    public a(final T A) 
    { 
     this.A = A; 

     //do calculations 
     //since constructor cannot return a value, pass to another function. 
     this.d = retnData(Integer.parseInt(A.toString()) != 100); //convert to an integer, the backwards way. 
    } 
    private boolean retnData(boolean test) 
    { 
     return test; 
    } 
} 
// IN ANOTHER CLASS 
transient a<Integer> b; 
boolean c = b.d = b.a(25); // throws an erorr: (Int) is not apporpriate for a<Integer>.a 

Java將不允許這種由於Java認爲是INT =整型,即使雙方接受相同的數據!並且由於泛型工作的方式,我不能設置b;因爲int類型的原始性。即使轉換爲整數也不起作用,因爲它仍然會拋出「類型錯誤」,我必須問是否存在某種解決方法,或者試圖使其工作無效?

+3

如果您不想混淆代碼,每個想幫助您的人都需要去混淆,這將會有很大的幫助。 –

回答

4

您試圖顯式調用構造函數作爲實例方法。這不能在Java中完成。

也許你想:

transient a<Integer> b = new a<Integer>(25); 
boolean c = b.d; 

然而,由於d被宣佈爲protected,只會如果這個代碼是從a或在同一個包派生另一個類的工作。

+0

這是正確的答案 – Igor

1

代碼中並沒有太大的意義:ba類型的對象,它不具有a方法 - 所以不知道你從b.a(25)的期望值; ......這有什麼好做int VS Integer。 ..

2

使用

final a<Integer> b = new a<Integer>(10); 
boolean c = b.d; 

INT可以顯式轉換到整數用new Integer(10)或Integer.valueOf(10)

+0

首選'Integer.valueOf(x)'到'Integer'構造函數。 (特別是,它保證將'Integer'對象緩存爲25.) –

+0

你總是可以將'int'傳遞給需要'Integer'的方法。 – assylias

+0

'a(Integer)'是一個構造函數。無論您是傳遞「int」還是「Integer」,都無法調用「b.a」。 –