```java
public class GenericClass<T> {
private T value;
public GenericClass(T value) {
this.value = value;
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
public static <E> void genericMethod(E item) {
System.out.println("Generic Method: " + item);
}
public static void main(String[] args) {
// 使用泛型類
GenericClass<String> stringClass = new GenericClass<>("Hello");
System.out.println("Generic Class Value: " + stringClass.getValue());
// 使用泛型方法
GenericClass.genericMethod(10);
}
}
```
### 通配符(Wildcard)
```java
import java.util.ArrayList;
import java.util.List;
public class GenericWildcardExample {
public static void printList(List<?> list) {
for (Object item : list) {
System.out.println(item);
}
}
public static void main(String[] args) {
List<String> stringList = new ArrayList<>();
stringList.add("Hello");
stringList.add("World");
List<Integer> integerList = new ArrayList<>();
integerList.add(10);
integerList.add(20);
printList(stringList);
printList(integerList);
}
}
```
### 泛型限定(Bounds)
```java
public class GenericBoundsExample {
public static <T extends Number> double sum(List<T> list) {
double total = 0.0;
for (T number : list) {
total += number.doubleValue();
}
return total;
}
public static void main(String[] args) {
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
double sum1 = sum(integerList);
System.out.println("Sum of integers: " + sum1);
List<Double> doubleList = Arrays.asList(1.1, 2.2, 3.3, 4.4, 5.5);
double sum2 = sum(doubleList);
System.out.println("Sum of doubles: " + sum2);
// 編譯錯誤,String 類型不符合限定條件
// List<String> stringList = Arrays.asList("one", "two", "three");
}
}
```