2015-10-19 56 views
2

我有點新到Java,但我真的很困惑,爲什麼這兩個「當量」的語句拋出不同的錯誤:仿製藥的私人實例

public class SampleArray<T> implements Grid<T> { 
    public int x; 
    public int y; 
    private List<List<T>> grid = new ArrayList<List<T>>(); 

    public SampleArray(int x, int y) { 
     this.x = x; 
     this.y = y; 
    } 
} 

這工作得很好,從瞭解它實例接受泛型類型T和一類具有X,Y和私人財產清單列出需要和T

public class SampleArray<T> implements Grid<T> { 
    public int x; 
    public int y; 
    private List<List<T>> grid; 

    public SampleArray(int x, int y) { 
     this.x = x; 
     this.y = y; 
     List<List<T>> this.grid = new ArrayList<List<T>>(); 
    } 
} 

這給了我一個錯誤,特別是:

Syntax Error insert ";" to complete LocalVariableDeclarationStatement; 
Syntax Error insert "VariableDelarators" to complete LocalVariableDeclaration 

正好在T>> this.grid的尖括號旁邊。爲什麼我得到這個錯誤?它們不是等同的,只是一個在不同的地方被實例化了嗎?界面網格只是一個通用接口

+1

這與泛型沒有任何關係。做int this.x = x;'也是無效的Java。爲什麼你在初始化this.grid時需要重複這個字段的類型? –

+0

哇......我覺得很......啞。非常感謝! –

回答

3

您正在構造函數中再次定義網格。試試這個

public SampleArray(int x, int y) { 
    this.x = x; 
    this.y = y; 
    this.grid = new ArrayList<List<T>>(); 
} 

改爲。它會將您的班級中的網格聲明爲私人領域。初始化在構造函數中完成。

private List<List<T>> grid = new ArrayList<List<T>>(); 

定義並在一匝初始化柵格。

6

第二段代碼的語法不好。在初始化this.grid時不應該重新指定數據類型;編譯器會認爲你正在聲明一個局部變量,並且this不能用於創建局部變量。

刪除變量上的數據類型。

this.grid = new ArrayList<List<T>>();