= Solution
A collections library can supply a genuinely <generic method in Java> whose own type parameter connects the input element and the result element type:
``
java
static <T> java.util.List<T> oneElement(T item) {
java.util.List<T> result = new java.util.ArrayList<T>();
result.add(item);
return result;
}
``
For example, `List<String> xs = oneElement("sample");` is type-checked without a cast. The method can also construct a `List<Integer>` from an integer object. The standard library's `Collections.singletonList` is another example of this type relationship, though its returned list is unmodifiable.
\b[The benefit is one reusable implementation with compile-time argument/result consistency.] A raw `List` result would lose element-type information, invite unchecked calls and require casts that may fail later. Separate methods for every element type would duplicate code. Merely enclosing a concrete type in angle brackets, such as returning `List<String>`, does not make a method generic; the method here declares `<T>`. <Type erasure> means the guarantee is primarily a source-level type check, not a distinct runtime class for each type argument.
Back to article page