代碼
提交代碼
public class KeyValueGeneric<K,V> { // 把兩個(gè)泛型K、V定義在類上
/**
* 類型為K的key屬性
*/
private K key;
/**
* 類型為V的value屬性
*/
private V value;
public K getKey() {
return key;
}
public void setKey(K key) {
this.key = key;
}
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
public static void main(String[] args) {
// 實(shí)例化對(duì)象,分別指定元素類型為整型、長(zhǎng)整型
KeyValueGeneric<Integer, Long> integerLongKeyValueGeneric = new KeyValueGeneric<>();
// 調(diào)用setter、getter方法
integerLongKeyValueGeneric.setKey(200);
integerLongKeyValueGeneric.setValue(300L);
System.out.println("key=" + integerLongKeyValueGeneric.getKey());
System.out.println("value=" + integerLongKeyValueGeneric.getValue());
// 實(shí)例化對(duì)象,分別指定元素類型為浮點(diǎn)型、字符串類型
KeyValueGeneric<Float, String> floatStringKeyValueGeneric = new KeyValueGeneric<>();
// 調(diào)用setter、getter方法
floatStringKeyValueGeneric.setKey(0.5f);
floatStringKeyValueGeneric.setValue("零點(diǎn)五");
System.out.println("key=" + floatStringKeyValueGeneric.getKey());
System.out.println("value=" + floatStringKeyValueGeneric.getValue());
}
}
運(yùn)行結(jié)果