开发者

What is static <E>?

开发者 https://www.devze.com 2023-01-11 03:40 出处:网络
I am just reading through collection java tutorial and wondering why开发者_C百科 the <E>is needed after static?

I am just reading through collection java tutorial and wondering why开发者_C百科 the <E> is needed after static?


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


Thanks, Sarah


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.

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.


The <E> is the way of declaring that this is a Generic Method a feature introduced with Generics in Java 5.0

See here for more details about its usage and rationale.

0

精彩评论

暂无评论...
验证码 换一张
取 消