The same is true for classes that can benefit from generics. Static tool methods are especially suitable for generics. All the methods in collections are generic.
An example of a union that returns two sets:
Static Set Union (set S1, set s2) { new HashSet (S1); Result.addall (S2); return result;}
There are two warnings, because the original ecological type set is used.
Generics the method:
Public Static <E> set<e> Union (set<e> S1, set<e> s2) { Setnew HashSet <E>(S1); Result.addall (S2); return result;}
The warning is no longer prompted because it is type-safe.
Generic Singleton factory: Sometimes it is necessary to create immutable but suitable objects of different types.
Suppose there is an interface with only one method that accepts and returns the value of a type T
Public Interface unaryfunction<t> { t apply (t arg);}
Suppose you want to provide an identity function that is wasteful if you recreate it every time you need it, and if generics are materialized, each type requires an identity function, but after they are erased, only one generic singleton is required.
Private Static unaryfunction<object> identity_function = new unaryfunction<object>() { @Override Public object Apply (object arg) { return arg; } }; @SuppressWarnings ("Unchecked") publicstatic <T> unaryfunction <T> indentityfunction () { return (unaryfunction<t>) identity_function;}
Recursive type restriction: restricts type parameters by an expression that contains the type parameter itself.
Public Interface Comparable<t> { int compareTo (T o) {}
Type restriction <t extends comparable<t>> for each type T that can be compared to itself
Public Static extends Comparable<t>> T Max (list<t> List) { Iterator<T> i = list.iterator (); = I.next; while (I.hasnext ()) { = i.next (); if (T.compareto (Result) > 0) = t; } return result;}
This method searches the list to find the maximum value in the list.
27th: The generic method is preferred