Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is static <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);
}


Thanks, Sarah

like image 560
sarahTheButterFly Avatar asked Aug 13 '10 00:08

sarahTheButterFly


People also ask

What is static E?

Static electricity is the result of an imbalance between negative and positive charges in an object. These charges can build up on the surface of an object until they find a way to be released or discharged. One way to discharge them is through a circuit.

What causes static E?

Static electricity is created when positive and negative charges aren't balanced. Protons and neutrons don't move around much, but electrons love to jump all over the place! When an object (or person) has extra electrons, it has a negative charge.

What is static electricity example?

Static electricity can be seen when a balloon is rubbed against one's hair, for example. Another common example is the shock one receives after walking across a carpet and then touching a door knob. Lightning is also the result of static electric discharge.


2 Answers

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.

like image 82
mdma Avatar answered Sep 28 '22 23:09

mdma


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.

like image 44
Jose Diaz Avatar answered Sep 29 '22 01:09

Jose Diaz