使类泛型有什么意义?

2023-12-30

当你有一个方法时,我知道将其声明为泛型是有意义的,这样我就可以采用泛型参数。像这样:

public <T> void function(T element) {
    // Some code...
}

但是,如果我可以简单地将每个方法声明为泛型,那么使整个类泛型背后的想法到底是什么?


好吧,区别在于,如果您尝试使类中的每个方法通用,那么您在第一个通用方法中使用的通用类型可能是相同的类型,也可能不是相同的类型。我的意思是。

public <T> void firstGenMethod(...){

}

public <T> void secondGenMethod(...){

}

Test:

  SomeClass ref = new SomeClass();
  ref.firstGenMethod("string");
  ref.secondGenMethod(123);//legal as this generic type is not related to the generic type which is used by firstGenMethod

在上述情况下,不能保证这两个方法具有相同的泛型类型。这取决于您如何调用它们。如果您将类设为通用,则该类型将应用于该类内的所有方法。

class Test<T>{

    public void firstGenMethod(T t){

    }

    public  void secondGenMethod(T t){

    }
}

Test:

 Test<String> testingString = new Test<>();
   testingString.firstGenMethod("abc");
   testingString.firstGenMethod(123);// invalid as your Test class only expects String in this case

您通常会使您的类变得通用,您希望该类的整个行为(方法)在同一类型上进行处理。最好的例子是班级的Java集合框架

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使类泛型有什么意义? 的相关文章

随机推荐