什么是静态< E> [英] What is static <E>?

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

问题描述

我只是阅读通过收集java教程,想知道为什么静态后需要< E>

I am just reading through collection java tutorial and wondering why the <E> is needed after static?



public static<E> Set<E> removeDups(Collection<E> c) {
    return new LinkedHashSet(c);
}


谢谢,
Sarah

Thanks, Sarah

推荐答案

为了可读性,通常在静态和通用参数名称之间有一个空格。 static 将该方法声明为静态,即没有实例需要调用它。 < E> 声明有一个称为E的无界通用参数,用于参数化方法的参数和/或返回值。这里,它在返回类型 Set< E> 中使用以声明该方法返回E的集合,并且在参数中 E> 表示该方法采用了E的集合。

For readability, there's usually a space between the static and the generic parameter name. static declares the method as static, i.e. no instance needed to call it. The <E> declares that there is an unbounded generic parameter called E that is used to parameterize the method's arguments and/or return value. Here, it's used in both the return type, Set<E> to declare the method returns a Set of E, and in the parameter, Collection<E> indicating that the method takes a collection of E.

未指定E的类型,只返回值和方法参数必须使用相同类型进行一般参数化。编译器在调用方法时确定实际类型。例如,

The type of E is not specified, only that the return value and the method parameter must be generically parameterized with the same type. The compiler determines the actual type when the method is called. For example,

   Collection<String> myStrings = new ArrayList<String>();
   .. add strings
   Set<String> uniqueStrings = SomeClass.removeDups(myStrings);

如果您尝试对两个集合使用不同的参数化类型,例如

If you attempt use different parameterized types for the two collections, such as

   Set<Integer> uniqueStrings = SomeClass.removeDups(myStrings);

这会产生编译器错误,因为通用参数不匹配。

this will generate a compiler error, since the generic parameters do not match.

这篇关于什么是静态&lt; E&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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