[Valid Java] 7. Give priority to generic methods, and define tivejava
Package cn. xf. cp. ch02.item27; import java. util. hashSet; import java. util. set; public class Union {/*** this method generates a warning * @ param s1 * @ param s2 * @ return */public static Set union1 (Set s1, Set s2) {Set result = new HashSet (s1); result. addAll (s2); return result ;} /*** the generic type is used here. * @ param s1 * @ param s2 * @ return */public static <E> Set <E> union (Set <E> s1, set <E> s2) {Set <E> result = new HashSet <E> (s1); result. addAll (s2); return result ;}}
However, sometimes we find that when using generics, We need to specify the generic type when calling the constructor, which is very troublesome for writing.
Here, a generic static method can be used to derive the generic type.
Package cn. xf. cp. ch02.item27; import java. util. hashMap; import java. util. list; import java. util. map; public class GenericStaticFactory {public static <K, V> HashMap <K, V> newHashMap () {return new HashMap <K, V> ();} public static void main (String [] args) {// when an object is created here, the map <String> is automatically converted according to the String and List <String> in the previous Map, list <String >> anagrams = newHashMap ();}}
Implementation of generic single-profit factory
Package cn. xf. cp. ch02.item27; public class GenericSingletonFactory {// create an object first, and temporarily replace the T Object private static UnaryFunction <Object> IDENTITY_FUNCTION = new UnaryFunction <Object> () {public Object apply (object arg) {return arg ;}; // according to T, the IDENTITY_FUNCTION is converted to the corresponding type, because the IDENTITY_FUNCTION returns the object type parameter that has not been modified, therefore, @ SuppressWarnings ("unchecked") public static <T> UnaryFunction <T> identityFunction () {return (UnaryFunction <T>) IDENTITY_FUNCTION ;} public static void main (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 (); // It is used to determine whether a single-instance Object t1 = sameString is actually implemented; Object t2 = sameNumber; if (t1 = t2) {System. out. println ("same reference");} String s1 = "123456"; String s2 = new String ("123456"); if (s1.equals (s2) System. out. println ("same content"); for (Number n: numbers) System. out. println (sameNumber. apply (n ));}}
Display result: