这是在Java中使用泛型的正确方法吗?

时间:2017-06-08 18:40:26

标签: java generics

class Matrix<T>{
   private List<Attribute<T>> attributes;

   public Matrix(T type){
      attributes = new ArrayList<Attribute<T>>();
      attributes.add(new Attribute<T>(type));
   }
}

我觉得在构造函数中,这两行应该使用特定的类型,而不是通用的T:

attributes = new ArrayList<Attribute<T>>();
      attributes.add(new Attribute<T>(type));

但是编译器并没有抱怨。那么这是定义这个类的正确方法吗?

2 个答案:

答案 0 :(得分:2)

是的,这是正确的方式。唯一可能出错的地方是构造函数中的参数不应该是namend类型,而是value。类型是T。

如果您需要,可以说您的Generic必须是其他类型的子类型。让我们说我们有一个持有异常的类。我们可以创建一个类型异常的Membervariable。但是当从这个Object中获取Exception时,我们不想将我们的Exception转换为更具体的异常。

所以我们使用Generic,它必须是Exception的子类型:

public class SomeClass<T extends Exception>
{
    private final T value;

    public SomeClass(T value)
    {
        this.value = value;
    }

    public T getValue()
    {
        return this.value;
    }
}

现在我们可以做这样的事情:

SomeClass<ArrayIndexOutOfBoundsException> obj = new SomeClass<>(new ArrayIndexOutOfBoundsException());
ArrayIndexOutOfBoundsException exc = obj.getValue(); // no cast from Exception to ArrayIndexOutOfBoundsException needed

答案 1 :(得分:1)

  

我觉得在构造函数中,这两行应该使用特定的类型,而不是泛型T

不,因为您的班级Matrix在类型参数T上是通用的。这意味着它封装了T类型的属性列表,即:List<Attribute<T>>

如果您将其与Integer一起使用:

Matrix<Integer> integerMatrix = new Matrix<>(1);

然后1将位于列表的第一个属性中。

但是,如果您使用String声明另一个矩阵:

Matrix<String> stringMatrix = new Matrix<>("hello");

然后,您的矩阵将包含封装String值的属性。

相关问题