該學習筆記只記錄了《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
先后保存了Automobile
、String
、Integer
等類型的對象,但是一般我們在實例化容器的時候都希望能夠指定它能夠保存的對象的類型,而不像這樣什么類型的對象都可以保存。
采用泛型版本的容器類
第三個版本:
// : 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 Holder
s, 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>
。
方法和類除了類型參數列表不同之外還有什么不一樣的嗎?把泛型當做普通的類就行了。