---
# System prepended metadata

title: 泛型的用法
tags: [ocpjp]

---

# 泛型的用法
**Question:**
```java=
class Foo<K,V>{
	private K key;
	private V value;
	public Foo(K key,V value) {
		this.key = key;
		this.value = value;
	}
	public static <T> Foo<T,T> twice(T value){
		return new Foo<T,T>(value,value);
	}
	public K getKey() {
		return key;
	}
	public V getValue() {
		return value;
	}
}
```
## Which option fails?
A. Foo<String, Integer> mark = new Foo<String, Integer> ("Steve", 100);
B. Foo<String, String> pair = Foo.<String>twice ("Hello World!");
**C. Foo<Object, Object> percentage = new Foo<String, Integer>("Steve", 100);**
D. Foo<String, String> grade = new Foo <> ("John", "A");
- [x] **Answer: C**

:::info
- 選項A，雖然是正確的泛型使用方式，但是在Java 7以後的版本，在實體化物件的時候，最好是省略new運算子泛型的型態，變成以下這樣：
```Java=
Foo<String, Integer> mark = new Foo<> ("Steve", 100);
```

- 選項B，正確的泛型使用方式。

- 選項C，錯誤的泛型使用方式。應改成以下這樣：
```Java=
Foo<Object, Object> percentage = new Foo<>("Steve", 100);
```
- 選項D，正確的泛型使用方式。
:::

###### tags: `ocpjp`