Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
// Generic class class Pair<A, B> { private final A first; private final B second; public Pair(A first, B second) { this.first = first; this.second = second; } public A getFirst() { return first; } public B getSecond() { return second; } @Override public String toString() { return "(" + first + ", " + second + ")"; } } // Generic method class Utils { public static <T> T last(java.util.List<T> list) { if (list.isEmpty()) throw new java.util.NoSuchElementException(); return list.get(list.size() - 1); } public static <T extends Comparable<T>> T max(T a, T b) { return a.compareTo(b) >= 0 ? a : b; } } public class GenericsDemo { public static void main(String[] args) { Pair<String, Integer> p = new Pair<>("Age", 30); System.out.println("Pair: " + p); System.out.println("First: " + p.getFirst()); java.util.List<Integer> nums = java.util.List.of(1, 2, 3, 9, 4); System.out.println("Last: " + Utils.last(nums)); System.out.println("Max(7,3): " + Utils.max(7, 3)); System.out.println("Max(apple,zebra): " + Utils.max("apple", "zebra")); } }
Result
Open