Generics
Generics provides a way to create classes, interfaces and methods.
Instead of using raw types (eg. Object), you define a placeholder for the type.
public class Box<T> {
public T item;
public void setItem(T item) {
this.item = item;
}
public T getitem() {
return item;
}
}
import java.net.Inet4Address;
import java.util.*;
import java.util.function.Consumer;
interface Pair<K, V> {
K getKey();
V getValue();
}
class OrderedPair<K, V> implements Pair<K, V> {
private K key;
private V value;
public OrderedPair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {return key;}
public V getValue() {return value;}
}
public class Main {
public static void main(String[] args) {
Pair<String, Integer> pair = new OrderedPair<>("hello", 1);
System.out.println(pair.getKey());
}
}