1. 程式人生 > >棟哥帶你學Java泛型

棟哥帶你學Java泛型

在說泛型之前先建三個類.
第一個、Person類
/*
 * 姓名 和 年齡
 * 構造 set/get  toString 
 * 建立一個學生類(構造方法) 繼承人類
 */
public class Person {
    private String name;
    private int age;
    public Person() {}
    public Person(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    public
String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { // TODO Auto-generated method stub
return this.name + " " +this.age; } } 第二個、Student類 public class Student extends Person{ public Student() { super(); // TODO Auto-generated constructor stub } public Student(String name, int age) { super(name, age); // TODO Auto-generated constructor stub
} } 第三個、Worker類 /* * 泛型類(泛型類宣告時 尖括號中的字母 你可以隨便定義) * 泛型類的型別 在初始化這個類的物件 確定 */ public class Worker<W, L> { // 利用泛型寫成員變數 private W w; private L l; // 利用泛型寫get/set方法 public W getW() { return w; } public void setW(W w) { this.w = w; } public L getL() { return l; } public void setL(L l) { this.l = l; } // 普通成員方法 public void sayHi() { System.out.println("hahaha"); } // 除了W 還能不能使用其他的泛型 例如L // public void sayHi(L l) { // System.out.println("hahaha"); // } // 宣告不同泛型的方法 在呼叫泛型方法的時候 指定泛型的型別 // <Z> 宣告一個泛型 只要宣告過的 才能使用 public<Z> void sayHi(Z z) { System.out.println(z); } // 靜態方法中 直接使用 W // 當你呼叫靜態方法的時候 可能還沒有物件 沒有物件就沒知指定泛型 所以不能用 public static <A> void fun(A a) { System.out.println(a); } // 工作 public void work() { System.out.println("天天搬磚 一天能搬400塊"); } }
泛型:就是表示集合中儲存的資料型別.
先看第一個Demo:
public class Demo01 {
    public static void main(String[] args) {
        //fun1();
        //fun2();
        //fun3();

        // 建立實現類物件
        InterAImpl impl = new InterAImpl();
        impl.fun("哈哈");
    }

    /**
     * 
     */
    public static void fun3() {
        // 建立泛型類
        Worker<String, Student> worker = new Worker<>();
        // 給屬性賦值
//      worker.setW("哈哈");
//      System.out.println(worker.getW());
//      worker.sayHi();
//      worker.sayHi(new Student());
        // 呼叫
        worker.sayHi("abcd");
        //呼叫靜態方法
        Worker.fun("haohao");
    }

    /**
     * 編譯器就會報錯
     */
    public static void fun2() {
        // 建立集合 儲存3學生
        ArrayList<Student> students = new ArrayList<>();
        students.add(new Student("張三", 18));
        students.add(new Student("李四", 17));
        students.add(new Student("王五", 16));
        // 獲取迭代器
        // 設定泛型 可以把執行期報錯 轉化到 編譯器期報錯
        Iterator<Student> iterator = students.iterator();
        while (iterator.hasNext()) {
            Student next = iterator.next();
            System.out.println(next);
        }
    }

    /**
     * 儲存字串
     */
    public static void fun1() {
        // 建立一個集合 儲存 a b c d 字串型別
        // <E> E就代表 要儲存的元素型別
        // 後面的尖括號 要跟前面填的泛型 保持一致
        // jdk1.7出來 菱形泛型
        // 如果前面聲明瞭泛型 後面泛型可以省略不寫 省略不寫 表示型別一致
        ArrayList<String> list = new ArrayList<String>();
        list.add("a");
        list.add("b");
        list.add("c");
        list.add("d");
        // 用迭代器遍歷一下
        ListIterator<String> listIterator = list.listIterator();
        while (listIterator.hasNext()) {
            // 新增泛型之後 可以省去 強轉型別的麻煩
            String next = listIterator.next();
            System.out.println(next);
        }
    }
}

// 泛型介面
interface InterA<Y> {
    public abstract void fun(Y y);
}
// 實現類
class InterAImpl implements InterA<String>{

    @Override
    public void fun(String y) {
        // TODO Auto-generated method stub
        System.out.println(y);
    }

}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/*
 * ? extends E(向下限定)
 * ?是子類 繼承 E是父類  ?只能是E類的 子類
 * ? super E(向上限定)
 * ? 是父類 E是子類  ?只能是E類的 父類
 */
public class Demo02 {
    public static void main(String[] args) {
        //fun1();
        // 呼叫一 直接傳入陣列
//      int[] array = {1, 2, 3,4, 5};
//      fun2(array);
//      // 呼叫二  直接傳入多個數
//      fun2(1,3,5,7,9);
        // Arrays 類方法 把陣列轉化為集合
        int[] array = {1, 2, 3, 4, 5};// 沒有進行自動裝箱
        // 把陣列 當做集合中的一個元素 轉為了集合
        List<int[]> asList = Arrays.asList(array);
        System.out.println(asList);
        Integer[] array2 = {1, 2, 3, 4, 5};// 自動裝箱為 Integer型別
        List<Integer> asList2 = Arrays.asList(array2);
        System.out.println(asList2);

        String[] array3 = {"aaa","bbb"};
        List<String> asList3 = Arrays.asList(array3);
        System.out.println(asList3);
        // 把ccc 新增到集合中
        // 使用asList陣列轉集合 得到一個集合
        // 注意:這個集合不允許進行新增或者刪除的操作
        // 這麼轉的意義何在? 可以呼叫集合的其它方法
        boolean isContains = asList3.contains("aaa");
        // asList3.add("ccc");
        System.out.println(isContains);
    }
    // int ... num 相當於 傳入的引數 是個陣列
    // int ... num 可以接收多個引數 只能是方法引數最後一個
    // jdk 1.5之後出來的
    public static void fun2(int ... num) {
        // 遍歷
        for (int i = 0; i < num.length; i++) {
            System.out.println(num[i]);
        }
    }
    /**
     * 
     */
    public static void fun1() {
        /*
         *  建立一個儲存人的集合 存兩人
         *  建立一個儲存學生的集合 存兩人
         */
        ArrayList<Person> pList = new ArrayList<>();
        pList.add(new Person("張三", 11));
        pList.add(new Person("李四", 11));

        ArrayList<Student> sList = new ArrayList<>();
        sList.add(new Student("王五", 11));
        sList.add(new Student("趙六", 12));
        // 學生的集合 全部新增到 人的集合中
        // ? extends Person 只能填Person的子類
        // pList.addAll(sList);
        sList.addAll(sList);
        System.out.println(pList);
        System.out.println(sList);
    }
}
import java.util.ArrayList;
import java.util.ListIterator;

/*
 * 集合中的刪除方法
 * 1.不使用迭代器
 * 2.使用迭代器
 */
public class Demo03 {
    public static void main(String[] args) {
        //fun1();

        //fun2();
        //fun3();
    }

    /**
     * 
     */
    public static void fun3() {
        // 建立一個集合 儲存a b c d e
        ArrayList<String> list = new ArrayList<>();
        list.add("a");
        list.add("b");
        list.add("b");
        list.add("c");
        list.add("d");
        // 增強for迴圈遍歷 底層使用迭代器遍歷
        // 增強for迴圈 只能 用來遍歷 也叫快速遍歷\
        // 雙層遍歷的時候 使用的比較多
        for (String string : list) {
            System.out.println(string);
        }
        System.out.println(list);
    }

    /**
     * 使用迭代器刪除
     */
    public static void fun2() {
        // 迭代器刪除
        // 建立一個集合 儲存a b c d e
            ArrayList<String> list = new ArrayList<>();
            list.add("a");
            list.add("b");
            list.add("b");
            list.add("c");
            list.add("d");
            list.add("e");
            ListIterator<String> listIterator = list.listIterator();
            while (listIterator.hasNext()) {
                if (listIterator.next().equals("b")) {
                    listIterator.remove();
                }
            }
            System.out.println(list);
    }

    /**
     * 要會的
     */
    public static void fun1() {
        // 建立一個集合 儲存a b c d e
        ArrayList<String> list = new ArrayList<>();
        list.add("a");
        list.add("b");
        list.add("b");
        list.add("c");
        list.add("d");
        list.add("e");
        // 不使用迭代器 遍歷
        // 如果集合中有b 就把b刪除
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).equals("b")) {
                // 先當引數傳進去 再進行自減
                list.remove(i--);
            }           
        }
        System.out.println(list);
    }
}
import java.util.ArrayList;
import java.util.Collections;

/*
 * 
 */
public class Demo04 {
    public static void main(String[] args) {
        //fun1();
        // 建立一個集合 存入5個學生 按學生年齡 進行排序
        ArrayList<Student> students = new ArrayList<>();
        students.add(new Student("張三", 18));
        students.add(new Student("李四", 17));
        students.add(new Student("王五", 23));
        students.add(new Student("趙六", 25));
        students.add(new Student("劉一", 19));
        sortByName(students);
        System.out.println(students);

    }
    // 按姓名比較
    public static void sortByName(ArrayList<Student> arrayList) {
        for (int i = 0; i < arrayList.size() - 1; i++) {
            for (int j = 0; j < arrayList.size() - 1 - i; j++) {
                if (arrayList.get(j).getName().compareTo(arrayList.get(j + 1).getName()) > 0) {
                    Collections.swap(arrayList, j, j + 1);
                }
            }
        }
    }
    /**
     * 按照年齡氣泡排序
     */
    public static void fun1() {
        // 建立一個集合 存入5個學生 按學生年齡 進行排序
        ArrayList<Student> students = new ArrayList<>();
        students.add(new Student("張三", 18));
        students.add(new Student("李四", 17));
        students.add(new Student("王五", 23));
        students.add(new Student("趙六", 25));
        students.add(new Student("劉一", 19));
        for (int i = 0; i < students.size() - 1; i++) {
            for (int j = 0; j < students.size() - 1 - i; j++) {
                if (students.get(j).getAge() > students.get(j + 1).getAge()) {
                    Student student = students.get(j);
                    students.set(j, students.get(j + 1));
                    students.set(j + 1, student);
                }
            }
        }
        System.out.println(students);
    }
}