当你有一个方法时,我明白声明它是通用的,这样我就可以采用通用参数。像这样:
public <T> void function(T element) {
// Some code...
}
但是,如果我可以简单地声明每个方法都是通用的,那么让整个类都通用的想法到底是什么?
最佳答案
好吧,不同之处在于,如果您尝试使类中的每个方法都成为泛型,那么您在 say firstGenericMethod 中使用的泛型类型可能是也可能不是同一类型。我的意思是。
public <T> void firstGenMethod(...){
}
public <T> void secondGenMethod(...){
}
测试:
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<String> testingString = new Test<>();
testingString.firstGenMethod("abc");
testingString.firstGenMethod(123);// invalid as your Test class only expects String in this case
您通常会在您希望该类的整个行为(方法)在同一类型上进行处理的地方使您的类通用。最好的例子是 Java Collection Framework
中的类关于java - 使类泛化有什么意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15022819/