《Java編程思想 Generics》讀書筆記一——泛型的基礎知識

該學習筆記只記錄了《Java編程思想 泛型》一章前面部分的基礎知識,這里沒有跟泛型無關的的知識。

不使用泛型怎么寫出通用的代碼

把參數或屬性的類型定義為基類

One way that object-oriented languages allow generalization(泛化) is through polymorphism(多態性).
Anything but a final class(Or a class with all private constructors) can be extended, so this flexibility is automatic much of the time.

把參數或屬性的類型定義為接口

Sometimes, being constrained to a single hierarchy is too limiting.Interfaces allow you to cut across class hierarchies.
------------------------分割線-------------------------------------------

泛型的概念——參數類型

Generics implement the concept of parameterized types, which allow multiple types. The term "generic" means "pertaining(與…有關的) or appropriate to large groups of classes."
Loosening the constraints on the types that those classes or methods work with.

效果

When you create an instance of a parameterized type, casts will be taken care of for you and the type correctness will been sured at compile time.
You tell generics what type you want to use, and it takes care of the details.
------------------------分割線-------------------------------------------

為什么使用泛型

One of the most compelling(引人注目的) initial(最初的) motivations for generics is to create container classes.
泛型剛開始是在容器類中使用的。下面的講解中使用的持有一個對象的容器,雖然只是持有一個對象,但是也是容器。

特定類型版本的容器類

// : generics/Holder1.java
class Automobile {
}


public class Holder1 {
    private Automobile a;

    public Holder1(Automobile a) {
        this.a = a;
    }

    Automobile get() {
        return a;
    }
}

上面這個類用途有限,因為支持保存Automobile對象,所以第二個版本就出來了:

類型為Object版本的容器類

// : generics/Holder2.java
public class Holder2 {
    private Object a;

    public Holder2(Object a) {
        this.a = a;
    }

    public void set(Object a) {
        this.a = a;
    }

    public Object get() {
        return a;
    }

    public static void main(String[] args) {
        Holder2 h2 = new Holder2(new Automobile());
        Automobile a = (Automobile) h2.get();
        h2.set("Not an Automobile");
        String s = (String) h2.get();
        h2.set(1); // Autoboxes to Integer
        Integer x = (Integer) h2.get();
    }
}

類型為Object版本的容器類的缺點

第二個版本是可以保存所有類型的對象了,但是:
There are some cases where you want a container to hold multiple types of objects, but typically you only put one type of object into a container. One of the primary motivations for generics is to specify what type of object a container holds, and to have that specification backed up by the compiler.
So instead of Object, we’d like to use an unspecified type, which can be decided at a later time.
上面的例子中Holder2類的對象h2先后保存了AutomobileStringInteger等類型的對象,但是一般我們在實例化容器的時候都希望能夠指定它能夠保存的對象的類型,而不像這樣什么類型的對象都可以保存。

采用泛型版本的容器類

第三個版本:

// : generics/Holder3.java
public class Holder3<T> {
    private T a;

    public Holder3(T a) {
        this.a = a;
    }

    public void set(T a) {
        this.a = a;
    }

    public T get() {
        return a;
    }

    public static void main(String[] args) {
        Holder3<Automobile> h3 = new Holder3<Automobile>(new Automobile());
        Automobile a = h3.get(); // No cast needed


        // The method set(Automobile) in the type Holder3<Automobile> is not applicable for the
        // arguments (String)
        // h3.set("Not an Automobile"); // Error


        // The method set(Automobile) in the type Holder3<Automobile> is not applicable for the
        // arguments (int)
        // h3.set(1); // Error
    }
}

Now when you create a Holders, you must specify what type you want to put into it using the same angle-bracket syntax, as you can see in main( ). You are only allowed to put objects of that type (or a subtype, since the substitution(代替) principle still works with generics) into the holder. And when you get a value out, it is automatically the right type.
------------------------分割線-------------------------------------------

在接口上使用泛型

// : net/mindview/util/Generator.java
// A generic interface.
package net.mindview.util;

public interface Generator<T> {
    T next();
}
import net.mindview.util.Generator;

class Phone {
}


public class PhoneGenerator implements Generator<Phone> {
    @Override
    public Phone next() {
        return new Phone();
    }
}

------------------------分割線-------------------------------------------

在方法上使用泛型

泛型化整個類還是某些方法?

The class itself may or may not be generic—this is independent of whether you have a generic method.
A generic method allows the method to vary independently of the class. As a guideline, you should use generic methods "whenever you can." That is, if it’s possible to make a method generic rather than the entire class, it’s probably going to be clearer to do so.

In addition, if a method is static, it has no access to the generic type parameters of the class, so if it needs to use genericity it must be a generic method.

在方法上使用泛型的例子

// : generics/GenericMethods.java
public class GenericMethods {
    public <T> void f(T x) {
        System.out.println(x.getClass().getName());
    }

    public static void main(String[] args) {
        GenericMethods gm = new GenericMethods();
        gm.f("");
        gm.f(1);
        gm.f(1.0);
        gm.f(1.0F);
        gm.f('c');
        gm.f(gm);
    }
}

類型參數推斷(使用泛型的方法的調用并需要賦值給另一個對象時才有的效果)

Notice that with a generic class, you must specify the type parameters when you instantiate the class. But with a generic method, you don’t usually have to specify the parameter types,because the compiler can figure that out for you. This is called type argument inference.

到底什么是類型參數推斷

package com.generics;

import java.util.HashMap;
import java.util.List;
import java.util.Map;



class Person {

}


class Pet {

}


public class App {
    static <T, U> Map<T, U> newMap() {
        return new HashMap<T, U>();
    }

    static void f(Map<Person, List<? extends Pet>> petPeople) {}

    public static void main(String args[]) {
        Map<Person, List<? extends Pet>> petPeople = new HashMap<Person, List<? extends Pet>>();
        // 有警告,警告內容如下
        // Type safety: The expression of type HashMap needs unchecked conversion to conform to
        // Map<Person,List<? extends Pet>>
        Map<Person, List<? extends Pet>> petPeople2 = new HashMap();
        // 沒有警告,很明顯App.newMap()可以推斷出返回的類型是Map<Person, List<? extends Pet>>
        Map<Person, List<? extends Pet>> petPeople3 = App.newMap();


        // 類型參數推斷只在賦值操作中有效
        // The method f(Map<Person,List<? extends Pet>>) in the type App is not applicable for the
        // arguments (Map<Object,Object>)
        // f(App.newMap());
    }
}

請一定要注意類型參數推斷只在賦值操作有效。

明確指明泛型方法返回值的類型

 f(App.<Person, List<? extends Pet>>newMap());

------------------------分割線-------------------------------------------

可變參數使用泛型

Generic methods and variable argument lists coexist nicely:

// : generics/GenericVarargs.java
import java.util.ArrayList;
import java.util.List;

public class GenericVarargs {
    // Type safety: Potential heap pollution via varargs parameter args
    public static <T> List<T> makeList(T... args) {
        List<T> result = new ArrayList<T>();
        for (T item : args)
            result.add(item);
        return result;
    }

    public static void main(String[] args) {
        List<String> ls = makeList("A");
        System.out.println(ls);
        ls = makeList("A", "B", "C");
        System.out.println(ls);
        ls = makeList("ABCDEFFHIJKLMNOPQRSTUVWXYZ".split(""));
        System.out.println(ls);
    }
}

------------------------分割線-------------------------------------------

Anonymous inner classes

Generics can also be used with inner classes and anonymous inner classes.

interface Generator<T> {
    T next();
}


class Book {
    private static long counter = 1;
    private final long id = counter++;

    private Book() {}

    public String toString() {
        return "Book " + id;
    }

    // A method to produce Generator objects:
    public static Generator<Book> generator() {
        return new Generator<Book>() {
            public Book next() {
                return new Book();
            }
        };
    }
}


public class InnerClassGeneric {
    public static void main(String args[]) {
        System.out.println(Book.generator().next());
    }
}

------------------------分割線-------------------------------------------

泛型跟其他類型的區別

In general, you can treat generics as if they are any other type—they just happen to have type parameters. But as you’ll see, you can use generics just by naming them along with their type argument list.
可以把泛型當做普通的類型,泛型就只要求你先使用類型參數列表命令它:

  • 類接口中
public class Holder3<T> {

上面的<T>

  • 方法中的
 public <T> void f(T x) {

上面的<T>
方法和類除了類型參數列表不同之外還有什么不一樣的嗎?把泛型當做普通的類就行了。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,247評論 6 543
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,520評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,362評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,805評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,541評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,896評論 1 328
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,887評論 3 447
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,062評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,608評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,356評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,555評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,077評論 5 364
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,769評論 3 349
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,175評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,489評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,289評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,516評論 2 379

推薦閱讀更多精彩內容