// Use of raw type for unknown element type - don't do this! - Page 113 staticintrawNumElementsInCommon(Set s1, Set s2) { intresult=0; for (Object o1 : s1) if (s2.contains(o1)) result++; return result; }
// Unbounded wildcard type - typesafe and flexible - Page 113 staticintnumElementsInCommon(Set<?> s1, Set<?> s2) { intresult=0; for (Object o1 : s1) if (s2.contains(o1)) result++; return result; } }
// The elements array will contain only E instances from push(E). // This is sufficient to ensure type safety, but the runtime // type of the array won't be E[]; it will always be Object[]! @SuppressWarnings("unchecked") publicStack() { elements = (E[]) newObject[DEFAULT_INITIAL_CAPACITY]; }
// IDENTITY_FUNCTION is stateless and its type parameter is // unbounded so it's safe to share one instance across all types. @SuppressWarnings("unchecked") publicstatic <T> UnaryFunction<T> identityFunction() { return (UnaryFunction<T>) IDENTITY_FUNCTION; }
// Sample program to exercise generic singleton publicstaticvoidmain(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(); for (Number n : numbers) System.out.println(sameNumber.apply(n)); } }