PackageCn.xf.cp.ch02.item27;ImportJava.util.HashSet;ImportJava.util.Set; Public classunion{/*** This method will have a warning *@paramS1 *@paramS2 *@return */ Public StaticSet Union1 (set S1, set s2) {Set result=NewHashSet (S1); Result.addall (S2); returnresult; } /*** The use of generics here is safe without warning *@paramS1 *@paramS2 *@return */ Public Static<E> set<e> Union (set<e> S1, set<e>S2) {Set<E> result =NewHashset<e>(S1); Result.addall (S2); returnresult; } }
But sometimes we find that when using generics, it is very difficult to write a generic type when invoking the constructor.
Here you can use a generic static method that takes advantage of the generic type deduction
PackageCn.xf.cp.ch02.item27;ImportJava.util.HashMap;Importjava.util.List;ImportJava.util.Map; Public classgenericstaticfactory{ Public Static<k, v> hashmap<k, v>Newhashmap () {return NewHashmap<k, v>(); } Public Static voidMain (string[] args) {//when the object is created, it is automatically converted according to the String and list<string> in the previous mapmap<string, list<string>> anagrams =Newhashmap (); }}
About the implementation of the generic simple interest plant
PackageCn.xf.cp.ch02.item27; Public classgenericsingletonfactory{//Create object objects first, temporarily override T objects Private StaticUnaryfunction<object> identity_function =NewUnaryfunction<object>() { Publicobject Apply (object arg) {returnArg; } }; //according to T, the identity_function is converted to the corresponding type, because Identity_function returns the object type parameter unmodified, so the following type conversion is safe@SuppressWarnings ("Unchecked") Public Static<T> unaryfunction<t>identityfunction () {return(unaryfunction<t>) identity_function; } Public Static voidMain (string[] args) {string[] strings= { "Jute", "hemp", "nylon" }; Unaryfunction<String> samestring =identityfunction (); for(String s:strings) System.out.println (samestring.apply (s)); Number[] Numbers= { 1, 2.0, 3L }; Unaryfunction<Number> Samenumber =identityfunction (); //This is used to determine if a single case is actually implemented.Object T1 =samestring; Object T2=Samenumber; if(T1 = =T2) {System.out.println ("Same Reference"); } String S1= "123456"; String S2=NewString ("123456"); if(s1.equals (S2)) System.out.println ("Same Content"); for(number N:numbers) System.out.println (samenumber.apply (n)); }}
Show Results:
"Effective Java" 7, preference for generic methods