Java泛型tutorial

Learning泛型class, 泛型method, class型parameter, 通配符, class型擦除 - core concepts

返回tutoriallist

Java泛型tutorial

Java泛型 is Java 5引入 一个 important features, 它允许 in 定义class, interface and method时usingclass型parameter, 使code更加flexible, class型security and reusable . 本tutorial将详细介绍Java泛型 core concepts and 实践techniques, helping您Master泛型programming 精髓.

1. 泛型overview

1.1 what is 泛型?

泛型 is aparameter化class型 mechanism, 它允许 in 定义class, interface and method时usingclass型parameter, 而不 is 具体 class型. class型parameter in using时被practicalclass型replace, from 而implementationcode 重用 and class型security.

1.2 泛型 优点

  • class型security: 泛型可以 in 编译时检测class型error, 而不 is in run时.
  • code重用: 泛型允许writing适用于 many 种class型 code, improvingcode reusability.
  • 消除强制class型转换: using泛型可以避免不必要 class型转换, 使code更加简洁.
  • 更 good code readable 性: 泛型可以使code 意graph更加明确, improvingcode readable 性.

2. 泛型class and interface

2.1 泛型class 定义

// 泛型class 定义
public class Box {
    private T content;
    
    public void setContent(T content) {
        this.content = content;
    }
    
    public T getContent() {
        return content;
    }
}

// using泛型class
public class BoxExample {
    public static void main(String[] args) {
        // creationstoreIntegerclass型 Box
        Box integerBox = new Box<>();
        integerBox.setContent(10);
        Integer integerValue = integerBox.getContent();
        System.out.println("Integer value: " + integerValue);
        
        // creationstoreStringclass型 Box
        Box stringBox = new Box<>();
        stringBox.setContent("Hello, Generics!");
        String stringValue = stringBox.getContent();
        System.out.println("String value: " + stringValue);
    }
}

2.2 泛型interface 定义

// 泛型interface 定义
public interface List {
    void add(T element);
    T get(int index);
    int size();
}

// implementation泛型interface
public class ArrayList implements List {
    private Object[] elements;
    private int size;
    
    public ArrayList(int capacity) {
        elements = new Object[capacity];
        size = 0;
    }
    
    @Override
    public void add(T element) {
        if (size < elements.length) {
            elements[size] = element;
            size++;
        }
    }
    
    @Override
    @SuppressWarnings("unchecked")
    public T get(int index) {
        if (index >= 0 && index < size) {
            return (T) elements[index];
        }
        throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
    }
    
    @Override
    public int size() {
        return size;
    }
}

// using泛型interface
public class ListExample {
    public static void main(String[] args) {
        List list = new ArrayList<>(10);
        list.add("Java");
        list.add("Generics");
        list.add("Tutorial");
        
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
    }
}

2.3 many class型parameter

//  many class型parameter 泛型class
public class Pair {
    private K key;
    private V value;
    
    public Pair(K key, V value) {
        this.key = key;
        this.value = value;
    }
    
    public K getKey() {
        return key;
    }
    
    public V getValue() {
        return value;
    }
    
    public void setKey(K key) {
        this.key = key;
    }
    
    public void setValue(V value) {
        this.value = value;
    }
}

// using many class型parameter 泛型class
public class PairExample {
    public static void main(String[] args) {
        Pair pair1 = new Pair<>("Age", 25);
        System.out.println("Key: " + pair1.getKey() + ", Value: " + pair1.getValue());
        
        Pair pair2 = new Pair<>(1, "Java");
        System.out.println("Key: " + pair2.getKey() + ", Value: " + pair2.getValue());
    }
}

3. 泛型method

3.1 泛型method 定义

public class GenericMethodExample {
    // 泛型method
    public static  void printArray(T[] array) {
        for (T element : array) {
            System.out.print(element + " ");
        }
        System.out.println();
    }
    
    // 带 has return value 泛型method
    public static  T getFirstElement(T[] array) {
        if (array != null && array.length > 0) {
            return array[0];
        }
        return null;
    }
    
    public static void main(String[] args) {
        // test泛型method
        Integer[] intArray = {1, 2, 3, 4, 5};
        String[] stringArray = {"Java", "Generics", "Method"};
        Double[] doubleArray = {1.1, 2.2, 3.3};
        
        System.out.println("Integer array:");
        printArray(intArray);
        
        System.out.println("String array:");
        printArray(stringArray);
        
        System.out.println("Double array:");
        printArray(doubleArray);
        
        // test带 has return value 泛型method
        System.out.println("First element of intArray: " + getFirstElement(intArray));
        System.out.println("First element of stringArray: " + getFirstElement(stringArray));
    }
}

3.2 class型parameter推断

in Java 7及以 on versionin, using泛型method时可以省略class型parameter, 编译器会根据 on under 文自动推断class型parameter.

public class TypeInferenceExample {
    public static  T getDefaultValue() {
        return null;
    }
    
    public static  void printValue(T value) {
        System.out.println(value);
    }
    
    public static void main(String[] args) {
        // 显式指定class型parameter
        String str1 = TypeInferenceExample.getDefaultValue();
        
        // class型parameter推断
        String str2 = getDefaultValue(); // 编译器推断T for String
        Integer num = getDefaultValue(); // 编译器推断T for Integer
        
        // method调用in class型parameter推断
        printValue("Hello"); // 编译器推断T for String
        printValue(42); // 编译器推断T for Integer
        printValue(3.14); // 编译器推断T for Double
    }
}

4. class型edge界

4.1 on 界通配符

on 界通配符usingextends关键字, 限制class型parameter必须 is 指定class型 or 其子class型.

public class UpperBoundExample {
    //  on 界通配符
    public static double sumOfList(List list) {
        double sum = 0.0;
        for (Number number : list) {
            sum += number.doubleValue();
        }
        return sum;
    }
    
    public static void main(String[] args) {
        List intList = new ArrayList<>();
        intList.add(1);
        intList.add(2);
        intList.add(3);
        System.out.println("Sum of intList: " + sumOfList(intList));
        
        List doubleList = new ArrayList<>();
        doubleList.add(1.1);
        doubleList.add(2.2);
        doubleList.add(3.3);
        System.out.println("Sum of doubleList: " + sumOfList(doubleList));
    }
}

4.2 under 界通配符

under 界通配符usingsuper关键字, 限制class型parameter必须 is 指定class型 or 其父class型.

public class LowerBoundExample {
    //  under 界通配符
    public static void addNumbers(List list) {
        for (int i = 1; i <= 5; i++) {
            list.add(i);
        }
    }
    
    public static void main(String[] args) {
        List intList = new ArrayList<>();
        addNumbers(intList);
        System.out.println("intList: " + intList);
        
        List numberList = new ArrayList<>();
        addNumbers(numberList);
        System.out.println("numberList: " + numberList);
        
        List objectList = new ArrayList<>();
        addNumbers(objectList);
        System.out.println("objectList: " + objectList);
    }
}
                
                
                

5. class型擦除

5.1 what is class型擦除?

class型擦除 is Java泛型 implementationmechanism, 它 in 编译时将泛型class型parameterreplace for 其edge界class型 (such as果没 has 指定edge界, 则replace for Object) , from 而生成非泛型 bytecode.

5.2 class型擦除 影响

  • run时无法获取泛型class型parameter practicalclass型
  • 不能usingbasicclass型serving as泛型class型parameter
  • 不能creation泛型class型 array
  • 不能 in 静态 on under 文inusing泛型class型parameter
public class TypeErasureExample {
    public static void main(String[] args) {
        Box intBox = new Box<>();
        Box stringBox = new Box<>();
        
        // class型擦除 after , intBox and stringBox class型都 is Box
        System.out.println("intBox.getClass(): " + intBox.getClass());
        System.out.println("stringBox.getClass(): " + stringBox.getClass());
        System.out.println("intBox.getClass() == stringBox.getClass(): " + (intBox.getClass() == stringBox.getClass()));
    }
}

class Box {
    private T content;
    
    public void setContent(T content) {
        this.content = content;
    }
    
    public T getContent() {
        return content;
    }
}

6. 泛型 限制

  • 不能usingbasicclass型serving asclass型parameter: such asList is 不允许 , 必须usingList.
  • 不能creation泛型class型 instance: such asnew T() is 不允许 .
  • 不能creation泛型class型 array: such asnew T[10] is 不允许 .
  • 不能 in 静态 on under 文inusing泛型class型parameter: 静态variable and method不能usingclass 泛型class型parameter.
  • 不能usinginstanceof运算符check泛型class型: such asinstanceof List is 不允许 .

实践case: 泛型toolclass

creation一个泛型toolclass, providing常用 泛型method, such asarray转collection, collection转array, 最 big 值findetc..

import java.util.ArrayList;
import java.util.List;

public class GenericUtils {
    // array转collection
    public static  List arrayToList(T[] array) {
        List list = new ArrayList<>();
        if (array != null) {
            for (T element : array) {
                list.add(element);
            }
        }
        return list;
    }
    
    // collection转array
    @SuppressWarnings("unchecked")
    public static  T[] listToArray(List list, T[] array) {
        if (list == null) {
            return null;
        }
        return list.toArray(array);
    }
    
    // find最 big 值
    public static > T findMax(T[] array) {
        if (array == null || array.length == 0) {
            return null;
        }
        T max = array[0];
        for (int i = 1; i < array.length; i++) {
            if (array[i].compareTo(max) > 0) {
                max = array[i];
            }
        }
        return max;
    }
    
    // 交换arrayin 两个元素
    public static  void swap(T[] array, int i, int j) {
        if (array != null && i >= 0 && i < array.length && j >= 0 && j < array.length) {
            T temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
    }
    
    // test泛型toolclass
    public static void main(String[] args) {
        // testarray转collection
        Integer[] intArray = {1, 2, 3, 4, 5};
        List intList = arrayToList(intArray);
        System.out.println("Array to List: " + intList);
        
        // testcollection转array
        String[] stringArray = listToArray(intList, new Integer[0]);
        System.out.println("List to Array: " + java.util.Arrays.toString(stringArray));
        
        // testfind最 big 值
        Integer[] numbers = {5, 2, 9, 1, 7};
        System.out.println("Max value: " + findMax(numbers));
        
        // test交换元素
        swap(numbers, 0, 2);
        System.out.println("After swap: " + java.util.Arrays.toString(numbers));
    }
}

这个泛型toolclass展示了such as何using泛型creationcommon toolmethod:

  1. using泛型methodimplementationarray and collection之间 转换
  2. using on 界通配符implementation最 big 值find
  3. using泛型methodimplementation元素交换

互动练习

练习1: implementation一个泛型栈

writing一个Java程序, implementation一个泛型栈, support以 under operation:

  1. push: 将元素压入栈顶
  2. pop: from 栈顶弹出元素
  3. peek: 查看栈顶元素但不弹出
  4. isEmpty: check栈 is 否 for 空
  5. size: 获取栈 big small

练习2: implementation泛型sortmethod

writing一个Java程序, implementation一个泛型sortmethod, able to for 任意implementation了Comparableinterface class型 arrayforsort.

练习3: implementation泛型cache

writing一个Java程序, implementation一个泛型cache, support以 under operation:

  1. put: 将键值 for 放入cache
  2. get: 根据键获取值
  3. remove: 根据键移除cache项
  4. clear: 清空cache
  5. size: 获取cache big small

© 2025 极客tutorial网. All Rights Reserved.

providing国 in 专业 programming入门tutorial及techniquesmanual

} .recommended-item a { text-decoration: none; color: #4285F4; font-weight: 500; } .recommended-item a:hover { text-decoration: underline; } /* 页脚 */ footer { background-color: #333; color: white; padding: 40px 0; text-align: center; } .footer-content { max-width: 800px; margin: 0 auto; } .footer-links { margin: 20px 0; } .footer-links a { color: white; text-decoration: none; margin: 0 10px; } .footer-links a:hover { text-decoration: underline; } /* response式design */ @media (max-width: 768px) { .nav-container { flex-direction: column; align-items: flex-start; } .nav-links { margin-top: 15px; flex-wrap: wrap; } .nav-links li { margin: 5px 10px 5px 0; } h1 { font-size: 2rem; } .section { padding: 20px; } h2 { font-size: 1.5rem; } h3 { font-size: 1.2rem; } }

Java泛型tutorial

MasterJava泛型programming, writingclass型security, reusable code

tutorialoverview

本tutorial将详细介绍Java泛型 core concepts and 实践techniques, including泛型class, 泛型method, class型parameter, 泛型edge界, 通配符, class型擦除etc. in 容. through本tutorial Learning, you willable towriting更加class型security, reusable Javacode, improvingcodequality and Developmentefficiency.

泛型overview

泛型 is Java 5引入 features, 它允许 in 定义class, interface and method时usingclass型parameter, 使得这些class, interface and methodable to适用于 many 种dataclass型, 而不需要 for 每种dataclass型writing重复 code.

泛型 优点

  • class型security: 泛型使得编译器able to in 编译时checkclass型, 避免run时class型转换error.
  • code重用: using泛型可以writing适用于 many 种dataclass型 commoncode, reducingcode重复.
  • readable 性: 泛型code更加清晰, 因 for class型parameter明确了code 意graph.
  • performanceoptimization: 泛型避免了run时class型转换, improving了程序performance.

泛型Basics

1. 泛型class

泛型class is 指 in 定义class时usingclass型parameter class. class型parameter in class名 after 面用尖括号<>括起来.

// 泛型class定义
public class Box<T> {
    private T content;
    
    public void setContent(T content) {
        this.content = content;
    }
    
    public T getContent() {
        return content;
    }
    
    public static void main(String[] args) {
        // creationstoreIntegerclass型 Box
        Box<Integer> integerBox = new Box<>();
        integerBox.setContent(100);
        Integer integerContent = integerBox.getContent();
        System.out.println("Integer in 容: " + integerContent);
        
        // creationstoreStringclass型 Box
        Box<String> stringBox = new Box<>();
        stringBox.setContent("Hello, Generics!");
        String stringContent = stringBox.getContent();
        System.out.println("String in 容: " + stringContent);
        
        // creationstoreDoubleclass型 Box
        Box<Double> doubleBox = new Box<>();
        doubleBox.setContent(3.14);
        Double doubleContent = doubleBox.getContent();
        System.out.println("Double in 容: " + doubleContent);
    }
}

2. 泛型method

泛型method is 指 in method声明inusingclass型parameter method. class型parameter in method返回class型 before 面用尖括号<>括起来.

// 泛型methodexample
public class GenericMethodExample {
    // 泛型method
    public static <T> void printArray(T[] array) {
        for (T element : array) {
            System.out.print(element + " ");
        }
        System.out.println();
    }
    
    // 带 has return value 泛型method
    public static <T> T getFirstElement(T[] array) {
        if (array != null && array.length > 0) {
            return array[0];
        }
        return null;
    }
    
    public static void main(String[] args) {
        // test泛型method
        Integer[] intArray = {1, 2, 3, 4, 5};
        String[] stringArray = {"Hello", "World", "Generics"};
        Double[] doubleArray = {1.1, 2.2, 3.3};
        
        System.out.println("整型array:");
        printArray(intArray);
        
        System.out.println("stringarray:");
        printArray(stringArray);
        
        System.out.println("双精度array:");
        printArray(doubleArray);
        
        // test带 has return value 泛型method
        System.out.println("整型array第一个元素: " + getFirstElement(intArray));
        System.out.println("stringarray第一个元素: " + getFirstElement(stringArray));
        System.out.println("双精度array第一个元素: " + getFirstElement(doubleArray));
    }
}

3. class型parameter命名约定

Java泛型 class型parameter通常using单个 big 写字母表示, 遵循以 under 命名约定:

  • T: Type (class型)
  • E: Element (元素)
  • K: Key (键)
  • V: Value (值)
  • N: Number (number)
  • R: Return Type (返回class型)

泛型edge界

泛型edge界用于限制class型parameter 范围, 使得class型parameter必须 is 某个specificclass型 子class or implementation了某个specificinterface.

1. on 限edge界

on 限edge界usingextends关键字, 表示class型parameter必须 is 指定class型 子class or implementation了指定interface.

// 泛型 on 限edge界example
public class GenericUpperBoundExample {
    // 泛型method, class型parameter on 限 for Number
    public static <T extends Number> double sum(T[] array) {
        double total = 0.0;
        for (T element : array) {
            total += element.doubleValue();
        }
        return total;
    }
    
    // 泛型class, class型parameter on 限 for Comparableinterface
    public static class GenericComparable<T extends Comparable<T>> {
        public T max(T[] array) {
            if (array == null || array.length == 0) {
                return null;
            }
            
            T maxValue = array[0];
            for (int i = 1; i < array.length; i++) {
                if (array[i].compareTo(maxValue) > 0) {
                    maxValue = array[i];
                }
            }
            return maxValue;
        }
    }
    
    public static void main(String[] args) {
        // test泛型method
        Integer[] intArray = {1, 2, 3, 4, 5};
        Double[] doubleArray = {1.1, 2.2, 3.3, 4.4, 5.5};
        
        System.out.println("整型array and : " + sum(intArray));
        System.out.println("双精度array and : " + sum(doubleArray));
        
        // test泛型class
        GenericComparable<Integer> intComparator = new GenericComparable<>();
        System.out.println("整型array最 big 值: " + intComparator.max(intArray));
        
        GenericComparable<String> stringComparator = new GenericComparable<>();
        String[] stringArray = {"Apple", "Banana", "Orange", "Pear"};
        System.out.println("stringarray最 big 值: " + stringComparator.max(stringArray));
    }
}

2. how heavyedge界

class型parameter可以 has many 个edge界, using&符号分隔. 注意, class必须 in before , interface in after .

// 泛型how heavyedge界example
interface Printable {
    void print();
}

class Animal {
    private String name;
    
    public Animal(String name) {
        this.name = name;
    }
    
    public String getName() {
        return name;
    }
}

class Dog extends Animal implements Printable {
    public Dog(String name) {
        super(name);
    }
    
    @Override
    public void print() {
        System.out.println("Dog: " + getName());
    }
}

class Cat extends Animal implements Printable {
    public Cat(String name) {
        super(name);
    }
    
    @Override
    public void print() {
        System.out.println("Cat: " + getName());
    }
}

public class GenericMultipleBoundsExample {
    // 泛型method, class型parameter必须 is Animal 子class且implementation了Printableinterface
    public static <T extends Animal & Printable> void printAnimal(T animal) {
        animal.print();
    }
    
    public static void main(String[] args) {
        Dog dog = new Dog("Buddy");
        Cat cat = new Cat("Whiskers");
        
        printAnimal(dog);
        printAnimal(cat);
    }
}

通配符

通配符用于表示未知class型, in 泛型codeinusing问号(?)表示. 通配符 has 三种形式: 无界通配符, on 界通配符 and under 界通配符.

1. 无界通配符

无界通配符using?表示, 表示可以匹配任何class型.

// 无界通配符example
public class UnboundedWildcardExample {
    // using无界通配符 method
    public static void printList(List<?> list) {
        for (Object element : list) {
            System.out.print(element + " ");
        }
        System.out.println();
    }
    
    public static void main(String[] args) {
        List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5);
        List<String> stringList = Arrays.asList("Hello", "World", "Generics");
        List<Double> doubleList = Arrays.asList(1.1, 2.2, 3.3);
        
        System.out.println("整型list:");
        printList(intList);
        
        System.out.println("stringlist:");
        printList(stringList);
        
        System.out.println("双精度list:");
        printList(doubleList);
    }
}

2. on 界通配符

on 界通配符using? extends T表示, 表示可以匹配T及其子class.

//  on 界通配符example
public class UpperBoundedWildcardExample {
    // using on 界通配符 method, 只能读取, 不能写入
    public static double sumList(List<? extends Number> list) {
        double total = 0.0;
        for (Number number : list) {
            total += number.doubleValue();
        }
        return total;
    }
    
    public static void main(String[] args) {
        List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5);
        List<Double> doubleList = Arrays.asList(1.1, 2.2, 3.3);
        List<Float> floatList = Arrays.asList(1.0f, 2.0f, 3.0f);
        
        System.out.println("整型list and : " + sumList(intList));
        System.out.println("双精度list and : " + sumList(doubleList));
        System.out.println("浮点型list and : " + sumList(floatList));
    }
}

3. under 界通配符

under 界通配符using? super T表示, 表示可以匹配T及其父class.

//  under 界通配符example
public class LowerBoundedWildcardExample {
    // using under 界通配符 method, 可以写入, 也可以读取 (但读取 to   is Objectclass型) 
    public static void addNumbers(List<? super Integer> list) {
        for (int i = 1; i <= 5; i++) {
            list.add(i);
        }
    }
    
    public static void main(String[] args) {
        // Integer 父classincludingNumber and Object
        List<Integer> intList = new ArrayList<>();
        List<Number> numberList = new ArrayList<>();
        List<Object> objectList = new ArrayList<>();
        
        System.out.println("=== testList<Integer> ===");
        addNumbers(intList);
        System.out.println("整型list: " + intList);
        
        System.out.println("=== testList<Number> ===");
        addNumbers(numberList);
        System.out.println("numberlist: " + numberList);
        
        System.out.println("=== testList<Object> ===");
        addNumbers(objectList);
        System.out.println("objectlist: " + objectList);
    }
}

class型擦除

Java泛型 is throughclass型擦除implementation , 这意味着 in 编译时, class型parameter会被擦除, replace for 它们 edge界class型 (such as果 has edge界) or Objectclass型 (such as果没 has edge界) .

class型擦除 影响

  • run时class型informationloss: 由于class型擦除, run时无法获取泛型 practicalclass型parameter.
  • 不能usingbasicclass型serving asclass型parameter: 因 for class型擦除 after 会replace for Object, 而basicclass型不 is Object 子class.
  • 不能creationclass型parameter instance: 因 for run时不知道具体 class型.
  • 不能creationclass型parameter array: 同样 is 因 for run时不知道具体 class型.
  • 不能 in 静态 on under 文inusingclass型parameter: 因 for class型parameter is and instance相关 , 而静态成员 is and class相关 .
// class型擦除example
public class TypeErasureExample {
    public static void main(String[] args) {
        // creation两个不同class型parameter Boxinstance
        Box<Integer> intBox = new Box<>();
        Box<String> stringBox = new Box<>();
        
        // run时class型相同, 都 is Box
        System.out.println("intBox run时class型: " + intBox.getClass());
        System.out.println("stringBox run时class型: " + stringBox.getClass());
        System.out.println("两个instance class型 is 否相同: " + (intBox.getClass() == stringBox.getClass()));
        
        // class型擦除 after , class型parameterinformationloss
        try {
            // through反射获取setContentmethod
            Method setContentMethod = intBox.getClass().getMethod("setContent", Object.class);
            System.out.println("setContentmethod parameterclass型: " + setContentMethod.getParameterTypes()[0]);
            
            // through反射获取getContentmethod
            Method getContentMethod = intBox.getClass().getMethod("getContent");
            System.out.println("getContentmethod 返回class型: " + getContentMethod.getReturnType());
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
}

// 泛型class定义
class Box<T> {
    private T content;
    
    public void setContent(T content) {
        this.content = content;
    }
    
    public T getContent() {
        return content;
    }
}

泛型best practices

  • 优先using泛型method: 当只 has method需要泛型时, using泛型method而不 is 泛型class.
  • using has 意义 class型parameter名: 虽然单个字母 is common , 但 in complex 泛型codein, using更 has 意义 名称可以improving readable 性.
  • 适当using通配符: 根据需要using on 界通配符 (用于读取) or under 界通配符 (用于写入) .
  • 避免原始class型: 原始class型 (such asList而不 is List<T>) 会失去泛型 class型security优势.
  • usingclass型parameter edge界: 当需要usingclass型parameter specificmethod时, usingedge界来限制class型parameter.
  • 注意class型擦除 影响: Understandclass型擦除 working principles, 避免 in run时依赖泛型class型information.
  • using@SuppressWarnings("unchecked")时要谨慎: 只 has in 确实无法避免未经check 转换时才using此注解.

实践case

泛型toolclass

本caseimplementation一个泛型toolclass, providing一些common toolmethod, such asarray转collection, collection转array, find最 big 值etc..

import java.util.*;

public class GenericUtils {
    /**
     * 将array转换 for collection
     * @param array 输入array
     * @param  array元素class型
     * @return 转换 after  collection
     */
    public static  List arrayToList(T[] array) {
        List list = new ArrayList<>();
        if (array != null) {
            Collections.addAll(list, array);
        }
        return list;
    }
    
    /**
     * 将collection转换 for array
     * @param collection 输入collection
     * @param  collection元素class型
     * @return 转换 after  array
     */
    @SuppressWarnings("unchecked")
    public static  T[] collectionToArray(Collection collection, T[] array) {
        return collection.toArray(array);
    }
    
    /**
     * findcollectionin 最 big 值
     * @param collection 输入collection
     * @param  collection元素class型, 必须implementationComparableinterface
     * @return collectionin 最 big 值
     */
    public static > T max(Collection collection) {
        if (collection == null || collection.isEmpty()) {
            return null;
        }
        
        Iterator iterator = collection.iterator();
        T max = iterator.next();
        
        while (iterator.hasNext()) {
            T current = iterator.next();
            if (current.compareTo(max) > 0) {
                max = current;
            }
        }
        
        return max;
    }
    
    /**
     * findcollectionin 最 small 值
     * @param collection 输入collection
     * @param  collection元素class型, 必须implementationComparableinterface
     * @return collectionin 最 small 值
     */
    public static > T min(Collection collection) {
        if (collection == null || collection.isEmpty()) {
            return null;
        }
        
        Iterator iterator = collection.iterator();
        T min = iterator.next();
        
        while (iterator.hasNext()) {
            T current = iterator.next();
            if (current.compareTo(min) < 0) {
                min = current;
            }
        }
        
        return min;
    }
    
    /**
     * copycollection
     * @param source sourcescollection
     * @param  collection元素class型
     * @return copy after   new collection
     */
    public static  List copyCollection(Collection source) {
        List destination = new ArrayList<>();
        if (source != null) {
            destination.addAll(source);
        }
        return destination;
    }
    
    /**
     * test泛型toolclass
     */
    public static void main(String[] args) {
        // testarrayToListmethod
        Integer[] intArray = {1, 2, 3, 4, 5};
        List intList = arrayToList(intArray);
        System.out.println("array转collection: " + intList);
        
        // testcollectionToArraymethod
        List stringList = Arrays.asList("Hello", "World", "Generics");
        String[] stringArray = collectionToArray(stringList, new String[0]);
        System.out.println("collection转array: " + Arrays.toString(stringArray));
        
        // testmaxmethod
        List numbers = Arrays.asList(10, 5, 8, 3, 12);
        System.out.println("最 big 值: " + max(numbers));
        
        // testminmethod
        System.out.println("最 small 值: " + min(numbers));
        
        // testcopyCollectionmethod
        List originalList = Arrays.asList("A", "B", "C");
        List copiedList = copyCollection(originalList);
        System.out.println("原始collection: " + originalList);
        System.out.println("copycollection: " + copiedList);
        System.out.println("两个collection is 否 is 同一个object: " + (originalList == copiedList));
    }
}

互动练习

练习1: 泛型classimplementation

creation一个泛型classPair<T, U>, 用于store一 for 不同class型 值. implementationgetFirst(), getSecond()method获取这两个值, 以及setFirst(), setSecond()method设置这两个值.

练习2: 泛型methodimplementation

implementation一个泛型methodswap(), 用于交换arrayin指定位置 两个元素. 该method应该适用于任何class型 array.

练习3: 泛型edge界using

creation一个泛型methodprintArea(), 用于打印各种graph形 面积. graph形classincludingCircle, Rectangleetc., 它们都implementation了Shapeinterface, 该interface has 一个getArea()method.

练习4: 通配符using

implementation一个methodprintList(), using无界通配符打印任何class型 list. 再implementation一个methodsumNumbers(), using on 界通配符计算任何numberclass型list and .