您的位置:首页 > 编程语言 > Java开发

黑马程序员——java编程那些事儿____jdk1.5新特性 泛型

2013-03-23 10:06 447 查看
-------android培训java培训、期待与您交流!
----------

总结了毕老师和张老师的泛型讲解,终于可理解泛型是怎么一回事了,哈哈

一 泛型概述

(1)为什么会出现泛型?

**因为集合存放的数据类型不固定,故往集合里面存放元素时,存在安全隐患,如果在定义集合时,可以像定义数组一样指定数据类型,那么就可以解

决该类安全问题。JDK1.5后出现了泛型,用于解决集合框架的安全问题。泛型是一个类型安全机制。

**Jdk 1.5以前的集合类中存在什么问题

ArrayList collection = new ArrayList();

collection.add(1);

collection.add(1L);

collection.add("abc");

int i = (Integer) collection.get(1);//编译要强制类型转换且运行时出错!

**Jdk 1.5的集合类希望你在定义集合时,明确表示你要向集合中装哪种类型的数据,无法加入指定类型以外的数据

ArrayList<Integer> collection2 = new ArrayList<Integer>();

collection2.add(1);

/*collection2.add(1L);

collection2.add(“abc”);*///这两行代码编译时就报告了语法错误

int i2 = collection2.get(0);//不需要再进行类型转换

**泛型是提供给javac编译器使用的,可以限定集合中的输入类型,让编译器挡住源程序中的非法输入,编译器编译带类型说明的集合时会

去除掉“类型”信息,使程序运行效率不受影响,对于参数化的泛型类型,getClass()方法的返回值和原始类型完全一样。由于编译生成的字节

码会去掉泛型的类型信息,只要能跳过编译器,就可以往某个泛型集合中加入其它类型的数据,例如,用反射得到集合,再调用其add方法即可。

(2)泛型定义格式:通过<>来定义要操作的引用数据类型

ArrayList<String> al = new ArrayList<String>;

//泛型
import java.util.*;
class GenericDemo
{
public static void main(String[] args)
{
ArrayList<String> al = new ArrayList<String>();
al.add("abc01");
al.add("abc0199");
al.add("abc0134");

//al.add(4);//相当于al.add(new Integer(4));jdk1.5出现的新特性自动装箱

Iterator<String> it = al.iterator();
while(it.hasNext())
{
String s = it.next();//强转避免了
System.out.println(s+":"+s.length());
}
}
}


(3)泛型的好处:

**将运行时期出现的ClassCastException(类型转换异常)问题转移到编译时期,方便于程序员解决问题,让运行时期问题减少,安全。

**避免了强制转换的麻烦

(4)什么时候定义泛型?

泛型在集合框架中很常见,只要见到<>就要定义泛型。其实<>就是用来接收类型的。

当使用集合时,将集合中要存储的数据类型作为参数传递到<>中即可

import java.util.*;
class GenericDemo2
{
public static void main(String[] args)
{
TreeSet<String> ts = new TreeSet<String>(new LenComparator());
ts.add("abcd");
ts.add("cc");
ts.add("cba");
ts.add("z");
ts.add("z");
ts.add("hahahah");

Iterator<String> it = ts.iterator();
while(it.hasNext())
{
String s = it.next();
System.out.println(s);
}
}
}
class LenComparator implements Comparator<String>//TreeSet排序的第二种方式,自定义一个比较器
{
public int compare(String o1,String o2)
{
int num = new Integer(o1.length()).compareTo(new Integer(o2.length()));//若将o1和o2互换则倒序输出
if(num==0)
return o1.compareTo(o2);//若将o1和o2互换则倒序输出
return num;
}
}


二 深入泛型

ArrayList<E>类定义和ArrayList<Integer>类引用中涉及如下术语:

整个称为ArrayList<E>泛型类型

ArrayList<E>中的E称为类型变量或类型参数

整个ArrayList<Integer>称为参数化的类型

ArrayList<Integer>中的Integer称为类型参数的实例或实际类型参数

ArrayList<Integer>中的<>念着typeof

ArrayList称为原始类型

参数化类型与原始类型的兼容性:

参数化类型可以引用一个原始类型的对象,编译报告警告,例如, Collection<String> c = new Vector();//可不可以,不就是编译器一句话的事吗?

原始类型可以引用一个参数化类型的对象,编译报告警告,例如, Collection c = new Vector<String>();//原来的方法接受一个集合参数,新的类型也要能传进去

参数化类型不考虑类型参数的继承关系:

Vector<String> v = new Vector<Object>(); //错误!///不写<Object>没错,写了就是明知故犯

Vector<Object> v = new Vector<String>(); //也错误!

编译器不允许创建泛型变量的数组。即在创建数组实例时,数组的元素不能使用参数化的类型,例如,下面语句有错误:

Vector<Integer> vectorList[] = new Vector<Integer>[10];

思考题:下面的代码会报错误吗?

Vector v1 = new Vector<String>();

Vector<Object> v = v1;

三 泛型的形式

**泛型类:即自定义泛型类

A:当类中要操作的引用数据类型不确定时,早期定义Object来完成扩展,现在定义泛型来完成

B:局限性:泛型类定义的泛型,在整个类中有效,如果该泛型类的方法被调用, 当泛型类的对象明确要操作的类型后,所有要操作的类型就被固定。

import java.util.*;

class Worker
{

}

//泛型前做法用Tool操作Worker
class Tool
{
private Object obj;
public void setObject(Object obj)
{
this.obj = obj;
}
public Object getObject()
{
return obj;
}
}

//泛型后做法用Utils操作Worker
/*
什么时候定义泛型类?
当类中要操作的引用数据类型不确定的时候,
早期定义Object来完成扩展。
现在定义泛型来完成扩展。
*/
class Utils<QQ>
{
private QQ q;
public void setObject(QQ q)
{
this.q = q;
}
public QQ getObject()
{
return q;
}
}

class GenericDemo3
{
public static void main(String[] args)
{
//用Utils操作Worker
Utils<Worker> u = new Utils<Worker>();

u.setObject(new Worker());
Worker w = u.getObject();

/*
//用Tool操作Worker
Tool t = new Tool();
t.setObject(new Worker());
Worker w = (Worker)t.getObject();

Tool t = new Tool();
t.setObject(new Worker());
t.getObject();
*/

}
}


张老师的高新讲解:

package cn.itcast.day2;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.sql.Date;
import java.util.Set;
import java.util.Vector;

import cn.itcast.day1.ReflectPoint;

import com.sun.org.apache.bcel.internal.generic.Type;

//dao操作 -->crud 增删改查

//定义泛型类
public class GenericDao<T> {

/**
* @param args
*/
public void add(T t){

}
public void delete(T obj){

}
public void delete(int id){

}
public void update(T obj){

}
/*
//当一个变量被声明为泛型时,只能被实例变量、方法和内部类调用,而不能被静态变量和静态方法调用。
//因为静态成员是被所有参数化的类所共享的,所以静态成员不应该有类级别的类型参数。
如果想用的话,就把泛型定义在方法上
public Static<T> void update2(T obj){

}
*/

//查集合
public Set<T> findByConditions(String where){
return null;
}
public T findByserName(String name){
return null;
}

public T findByTd(int id){
return null;
}

public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
GenericDao<ReflectPoint> dao = new GenericDao<ReflectPoint>();
dao.add(new ReflectPoint(3,3));
/*
//知识点   通过反射获得泛型的参数化类型
Method applyMethod = GenericDao.class.getMethod("applyVector",Vector.class);
Type[] types = applyMethod.getGenericParameterTypes();
ParameterizedType pType = (ParameterizedType)types[0];
System.out.println(pType.getRawType());//得到原始类型//class java.util.Vector
System.out.println(pType.getActualTypeArguments()[0]);//得到实际参数类型//class java.util.Date
*/
}

}
package cn.itcast.day1;

public class ReflectPoint {

/**
* @param args
*/
private int x;
public int y;
public ReflectPoint(int x,int y){
this.x = x;
this.y = y;
}

public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final ReflectPoint other = (ReflectPoint) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}

}


**泛型方法:泛型放在返回值前面,修饰符的后面

A:为了避免泛型类的局限性,让不同方法可以操作不同的类型,而且类型还不确定,则可以将泛型定义在方法上

B:特殊之处:静态方法不可以访问类上定义的泛型,如果静态方法操作的应用数据类型不确定,可以将泛型定义在静态方法上

import java.*;

/*
//泛型类,将泛型定义在类上
class Demo<T>
{
public void show(T t)
{
System.out.println("Hello show!"+t);
}
public void print(T t)
{
System.out.println("Hello print!"+t);
}
}
*/

/*
泛型类定义的泛型,在整个类中有效。如果被方法使用,
那么泛型类的对象明确要操作的具体类型后,所有要操作的类型就已经固定了。
为了让不同方法可以操作不同类型,而且类型还不确定。
那么可以将泛型定义在方法上。
*/

//泛型方法,将泛型定义在方法上
class Demo
{
public <T> void show(T t)
{
System.out.println("Hello show!"+t);
}
public <Q> void print(Q q)
{
System.out.println("Hello print!"+q);
}

/*
特殊之处:
静态方法不可以访问类上定义的泛型。
如果静态方法操作的应用数据类型不确定,可以将泛型定义在方法上。
*/
public  static <W> void method(W t)
{
System.out.println("method:"+t);
}

}

class GenericDemo4
{
public static void main(String[] args)
{
//泛型方法的
Demo d = new Demo();
d.show("hahah");
d.show(new Integer(4));

/*
//泛型类的

Demo<String> d = new Demo<String>();
d.show("haha");
d.print("xiix");

Demo<Integer> d = new Demo<Integer>();
d.show(new Integer(4));//同下,新特性
d.print(5);//同上新特性,
*/

}
}


张老师高新讲解:

package cn.itcast.day2;

import java.sql.Date;
import java.util.*;
import java.awt.image.DataBuffer;
import java.lang.reflect.*;

import com.sun.org.apache.bcel.internal.generic.Type;

public class GenericTest {

public static void main(String[] args) throws Exception{

//知识点   泛型集合类的综合案例
HashMap<String,Integer> map = new HashMap<String,Integer>();
map.put("zxx", 28);
map.put("lhm", 35);
map.put("flx", 33);

Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
for(Map.Entry<String, Integer> entry : entrySet)
{
System.out.println(entry.getKey() + ":" + entry.getValue());
}
/*
Set<Map.Entry<Student,String>> entrySet = hm.entrySet();
Iterator<Map.Entry<Student,String>> ite = entrySet.iterator();
while(ite.hasNext())
{
Map.Entry<Student,String> me = ite.next();
Student stu = me.getKey();
String addr = me.getValue();
System.out.println(stu+"\\\\"+addr);
}*/

add(3,5);
Number x1 = add(3.5,3);
Object x2 = add(3,"abc");

swap(new String[]{"abc","xyz","itcast"},1,2);//只有引用类型才能作为泛型方法的实际参数,对于add方法,
//使用基本类型的数据进行测试没有问题,这是因为自动装箱和拆箱了。 swap(new int[3],3.5);语句会报告编译错误,
//这是因为编译器不会对new int[3]中的int自动拆箱和装箱了,
//因为new int[3]本身已经是对象了,你想要的有可能就是int数组呢?它装箱岂不弄巧成拙了。

Object obj = "abc";
String x3 = autoConvert(obj);

copy1(new Vector<String>(),new String[10]);

copy2(new Date[10],new String[10]);

}
private static <T> void swap(T[] a,int i,int j)
{
T tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}

//定义泛型方法
private static <T> T add(T x,T y)
{
return null;
}

//以下是泛型方法的练习

//定义一个方法,把任意参数类型的集合中的数据安全地复制到相应类型的数组中
public static <T> void copy1(Collection<T> dest,T[] str){

}

//定义一个方法,把任意参数类型的一个数组中的数据安全地复制到相应类型的另一个数组中。
public static <T> void copy2(T[] dest,T[] src){

}

//采用自定泛型方法的方式打印出任意参数化类型的集合中的所有内容。
public static<T> void printCollection2(Collection<T> collection){

System.out.println(collection.size());
for(Object obj : collection)
{
System.out.println(obj);
}
}

//定义一个方法,可以将任意类型的数组中的所有元素填充为相应类型的某个对象。
private static <T> void fillArray(T[] a,T obj)
{
for(int i=0;i<a.length;i++)
{
a[i] = obj;
}
}
//编写一个泛型方法,自动将Object类型的对象转换成其他类型。
private static <T> T autoConvert(Object obj)
{
return (T)obj;
}

}


C 类型参数的类型推断

编译器判断范型方法的实际类型参数的过程称为类型推断,类型推断是相对于知觉推断的,其实现方法是一种非常复杂的过程。

根据调用泛型方法时实际传递的参数类型或返回值的类型来推断,具体规则如下:

当某个类型变量只在整个参数列表中的所有参数和返回值中的一处被应用了,那么根据调用方法时该处的实际应用类型来确定,这很容易凭着感觉推断出来,即直接根据调用方法时传递的参数类型或返回值来决定泛型参数的类型,例如:

swap(new String[3],3,4)  static <E> void swap(E[] a, int i, int j)

当某个类型变量在整个参数列表中的所有参数和返回值中的多处被应用了,如果调用方法时这多处的实际应用类型都对应同一种类型来确定,这很容易凭着感觉推断出来,例如:

add(3,5)  static <T> T add(T a, T b)

当某个类型变量在整个参数列表中的所有参数和返回值中的多处被应用了,如果调用方法时这多处的实际应用类型对应到了不同的类型,且没有使用返回值,这时候取多个参数中的最大交集类型,例如,下面语句实际对应的类型就是Number了,编译没问题,只是运行时出问题:

fill(new Integer[3],3.5f)  static <T> void fill(T[] a, T v)

当某个类型变量在整个参数列表中的所有参数和返回值中的多处被应用了,如果调用方法时这多处的实际应用类型对应到了不同的类型, 并且使用返回值,这时候优先考虑返回值的类型,例如,下面语句实际对应的类型就是Integer了,编译将报告错误,将变量x的类型改为float,对比eclipse报告的错误提示,接着再将变量x类型改为Number,则没有了错误:

int x =(3,3.5f)  static <T> T add(T a, T b)

参数类型的类型推断具有传递性,下面第一种情况推断实际参数类型为Object,编译没有问题,而第二种情况则根据参数化的Vector类实例将类型变量直接确定为String类型,编译将出现问题:

copy(new Integer[5],new String[5])  static <T> void copy(T[] a,T[] b);

copy(new Vector<String>(), new Integer[5])  static <T> void copy(Collection<T> a , T[] b);

**泛型接口:

当泛型定义在接口上时,则子类中要指定实现接口类型,同时还可以子类也可以定义为泛型类

//泛型定义在接口上。
interface Inter<T>
{
void show(T t);
}

/*
class InterImpl implements Inter<String>
{
public void show(String t)
{
System.out.println("show :"+t);
}
}

*/

class InterImpl<T> implements Inter<T>
{
public void show(T t)
{
System.out.println("show :"+t);
}
}
class GenericDemo5
{
public static void main(String[] args)
{

InterImpl<Integer> i = new InterImpl<Integer>();
i.show(4);
//InterImpl i = new InterImpl();
//i.show("haha");
}
}


四 泛型限定

*** ?通配符

当指定两种泛型的集合,则迭代时也要定义两种泛型的迭代器,麻烦,此时可通过将迭代器的泛型改为?,如Iterator<?> it=al.iterator();

问题:

定义一个方法,该方法用于打印出任意参数化类型的集合中的所有数据,该方法如何定义呢?

错误方式:

public static void printCollection(Collection<Object> cols) {
for(Object obj:cols) {
System.out.println(obj);
}
/* cols.add("string");//没错
cols = new HashSet<Date>();//会报告错误!*/
}


正确方式:

public static void printCollection(Collection<?> cols) {
for(Object obj:cols) {
System.out.println(obj);
}
//cols.add("string");//错误,因为它不知自己未来匹配就一定是String
cols.size();//没错,此方法与类型参数没有关系
cols = new HashSet<Date>();
}


总结:

使用?通配符可以引用其他各种参数化的类型,?通配符定义的变量主要用作引用,可以调用与参数化无关的方法,不能调用与参数化有关的方法。

**** 两种泛型限定

限定通配符的上边界: 向上限定: ? extends E ;E可以接收E类型或者E的子类

正确:Vector<? extends Number> x = new Vector<Integer>();

错误:Vector<? extends Number> x = new Vector<String>();

限定通配符的下边界: 向下限定: ? super E ;E可以接收E类型或者E的父类

正确:Vector<? super Integer> x = new Vector<Number>();

错误:Vector<? super Integer> x = new Vector<Byte>();

提示:

限定通配符总是包括自己。?只能用作引用,不能用它去给其他变量赋值

Vector<? extends Number> y = new Vector<Integer>();

Vector<Number> x = y;

上面的代码错误,原理与Vector<Object > x11 = new Vector<String>();相似,

只能通过强制类型转换方式来赋值。

import java.util.*;
class GenericDemo6
{
/*
public static void main(String[] args)
{

ArrayList<String> al = new ArrayList<String>();
al.add("abc1");
al.add("abc2");
al.add("abc3");

ArrayList<Integer> al1 = new ArrayList<Integer>();
al1.add(4);
al1.add(5);
al1.add(6);

printColl(al);
printColl(al1);

}

//单独封装一个类,提高代码复用性
public static void printColl(ArrayList<?> al)//通配符
{
Iterator<?> it = al.iterator();
while (it.hasNext())
{
System.out.println(it.next());
}
}

*/

public static void main(String[] args)
{
ArrayList<Person> al = new ArrayList<Person>();
al.add(new Person("abc1"));
al.add(new Person("abc2"));
al.add(new Person("abc3"));

//printColl(al);

ArrayList<Student> al1 = new ArrayList<Student>();
al1.add(new Student("abc...1"));
al1.add(new Student("abc...2"));
al1.add(new Student("abc...3"));

printColl(al1);

}

public static void printColl(ArrayList<? extends Person> al1)//<? extends E>//泛型的限定,上限
{
Iterator<? extends Person> it = al1.iterator();
while (it.hasNext())
{
System.out.println(it.next().getName());
}
}
}

class Person
{
private String name;

Person(String name)
{
this.name = name;
}

public String getName()
{
return name;
}
public String toString()
{
return "person:"+name;
}

}
class Student extends Person
{
Student(String name)
{
super(name);
}
}


//泛型限定二
import java.util.*;
class GenericDemo7
{
public static void main(String[] args)
{
TreeSet<Student> ts = new TreeSet<Student>(new Comp());
ts.add(new Student("abc03"));
ts.add(new Student("abc02"));
ts.add(new Student("abc01"));
ts.add(new Student("abc06"));
Iterator<Student> it = ts.iterator();
while(it.hasNext());
{
System.out.println(it.next().getName());
}

TreeSet<Worker> ts1 = new TreeSet<Worker>(new Comp());
ts1.add(new Worker("abc..03"));
ts1.add(new Worker("abc..02"));
ts1.add(new Worker("abc..01"));
ts1.add(new Worker("abc..06"));
Iterator<Worker> it1 = ts1.iterator();
while(it1.hasNext());
{
System.out.println(it1.next().getName());
}

}

}
/*

class StuComp implements Comparator<Student>
{
public int compare(Student s1,Student s2)
{
return s1.getName().compareTo(s2.getName());
}
}

class WorComp implements Comparator<Worker>
{
public int compare(Worker w1,Worker w2)
{
return w1.getName().compareTo(w2.getName());
}
}
*/

class Comp implements Comparator<Person>//泛型的限定< ? super E>  下限
{
public int compare(Person p1,Person p2)
{
return p1.getName().compareTo(p1.getName());
}
}

class Person
{
private String name;

Person(String name)
{
this.name = name;
}

public String getName()
{
return name;
}
public String toString()
{
return "person:"+name;
}

}
class Student extends Person
{
Student(String name)
{
super(name);
}
}
class Worker extends Person
{
Worker(String name)
{
super(name);
}
}


-------android培训java培训、期待与您交流!
----------
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: