~/ learn/ java-from-zero/ cards/ Generic methods: declaring and calling
1 of 4

Type a generic method that returns the first element or null

Type a generic method that returns the first element or null

Answer

public static <T> T firstOrNull(List<T> xs) { return xs.isEmpty() ? null : xs.get(0); }

<T> before the return type declares the type parameter for this method only. The caller passes a List<String> and the return type is String — no cast.

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/8fa37489-d406-4464-b339-c068afe9014a/flashcard utf-8 LF