使类通用的是什么? [英] What is the point of making a class generic?

查看:104
本文介绍了使类通用的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当你有一个方法,我知道有意义的声明它的泛型,所以我可以采用通用参数。像这样:

when you have a method, I understand that it makes sense to declare it generic so that i can take generic arguments. Like this:

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

推荐答案

但是,如果我可以简单地声明每个方法都是通用的,区别是如果你试图让你的类中的每个方法通用的通用类型,你将使用在你的第一个GenericMethod可能或可能不是相同的类型。我的意思是。

Well, the difference is if you try to make each method in your class generic the generic type you'd use in your say firstGenericMethod may or may not be the same type.What i mean is.

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

在上面的例子中,没有gaurentee,两个方法有相同的泛型类型。它取决于你如何调用它们。如果你使类通用,类型应用于该类中的所有方法。

In the above case there is no gaurentee that both the methods have the same generic type.It depends on how you invoke them. If you make the class generic though, the type is applied to all the methods inside that class.

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

You'd usually make your class generic where you'd want the entire behaviour(methods) of that class to process on the same type. best examples are class's in Java Collection Framework

这篇关于使类通用的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆