2015-10-19 46 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>>();