《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
先后保存了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>
。
方法和类除了类型参数列表不同之外还有什么不一样的吗?把泛型当做普通的类就行了。