From: gumartinm Date: Wed, 12 Oct 2011 18:22:15 +0000 (+0200) Subject: Effective Java 2nd Edition: X-Git-Url: https://git.gumartinm.name/?a=commitdiff_plain;h=3d7b4da19eebe30e8ca5ea1a82ac5bc44973166c;p=JavaForFun Effective Java 2nd Edition: Item 27 Change-Id: Idc2ff6e5e807e32961a9da4e7531b8133c7917c0 Signed-off-by: gumartinm --- diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..cc9a220 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +bin/ +.classpath +.project diff --git a/EffectiveJava2nd/Item27/src/test/GenericStaticFactory.java b/EffectiveJava2nd/Item27/src/test/GenericStaticFactory.java new file mode 100644 index 0000000..74030dd --- /dev/null +++ b/EffectiveJava2nd/Item27/src/test/GenericStaticFactory.java @@ -0,0 +1,24 @@ +package test; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class GenericStaticFactory { + + /** + * @param args + */ + public static void main(String[] args) { + // Parameterized type instance creation with constructor + Map> anagramsRedundancy = new HashMap>(); + + // Parameterized type instance creation with static factory. Without type parameters explicitly + // when invoking generic constructors (it is annoying...) + Map> anagrams = newHashMap(); + } + + public static HashMap newHashMap() { + return new HashMap(); + } +} diff --git a/EffectiveJava2nd/Item27/src/test/SingletonFactory.java b/EffectiveJava2nd/Item27/src/test/SingletonFactory.java new file mode 100644 index 0000000..2b195eb --- /dev/null +++ b/EffectiveJava2nd/Item27/src/test/SingletonFactory.java @@ -0,0 +1,39 @@ +/** + * + */ +package test; + +/** + * @author gusarapo + * + */ +public class SingletonFactory { + + private static UnaryFunction IDENTITY_FUNCTION = + new UnaryFunction() { + public Object apply(Object arg) + { + return arg; + } + }; + /** + * @param args + */ + public static void main(String[] args) { + String[] strings = {"jute", "hemp", "nylon"}; + UnaryFunction sameString = identityFunction(); + for (String s : strings) + System.out.println(sameString.apply(s)); + + Number [] numbers = {1, 2.0, 3L }; + UnaryFunction sameNumber = identityFunction(); + for (Number n : numbers) + System.out.println(sameNumber.apply(n)); + } + + @SuppressWarnings("unchecked") + public static UnaryFunction identityFunction() { + return (UnaryFunction) IDENTITY_FUNCTION; + } + +} diff --git a/EffectiveJava2nd/Item27/src/test/UnaryFunction.java b/EffectiveJava2nd/Item27/src/test/UnaryFunction.java new file mode 100644 index 0000000..e212f1e --- /dev/null +++ b/EffectiveJava2nd/Item27/src/test/UnaryFunction.java @@ -0,0 +1,12 @@ +/** + * + */ +package test; + +/** + * @author gustavo + * + */ +public interface UnaryFunction { + T apply (T arg); +}