Sobes.tech
Middle

How to create a static generic method in Java?

sobes.tech AI

Answer from AI

The declaration of a static generic method looks like this:

class MyUtils {

    // T is a type parameter declared before the return type
    public static <T> T firstElement(List<T> list) {
        if (list == null || list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    // You can declare multiple type parameters
    public static <K, V> K firstKey(Map<K, V> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }
        return map.keySet().iterator().next();
    }
}

Key points:

  • Type parameters are declared before the method's return type.
  • The rest of the method syntax is standard (access modifiers, static keyword, method name, parameters).
  • Type parameters can be used in the method signature: in the return type and/or in the parameter types.
  • The method is called like a regular static method, often without explicitly specifying the type, as the Java compiler can usually infer it:
List<String> names = Arrays.asList("Alice", "Bob");
String first = MyUtils.firstElement(names); // Compiler infers T as String

Map<Integer, String> numbers = new HashMap<>();
numbers.put(1, "One");
Integer key = MyUtils.firstKey(numbers); // Compiler infers K as Integer and V as String
  • If necessary, the type can be explicitly specified:
Integer explicitFirst = MyUtils.<Integer>firstElement(Arrays.asList(1, 2, 3));
How to create a static generic method in Java? — Java - sobes.tech