java编程思想笔记(九)泛型

白诗秀儿 关注

收藏于 : 2017-05-23 14:53   被转藏 : 1   

泛型:JAVA5时引入,泛型实现了参数化类型的概念,使代码可以应用于多种类型.

常用的泛型实现:<T> /<k,v>/Object/<?>/<? extends xxx>/<?  super xxx>

 

1.泛型类/接口:

(1).泛型接口:

如一个提供产生指定类的接口:

public interface Gernerator<T>{  
    T next() ;  
}  
public class A implement Generator<A>{  
    A next(){  
        return new A();  
    }  
}  

 

 

 (2).泛型类:

public class Test1<T>{  
}

 

 

2.泛型方法:

例如:

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);  
    ……  
}   
}  

 

 

输出结果为:

java.lang.String

java.lang.Integer

java.lang.Double

 

3.泛型集合:

Java中泛型集合使用的非常广泛,在Java5以前,java中没有引入泛型机制,使用java集合容器时经常遇到如下两个问题:

a.  java容器默认存放Object类型对象,如果一个容器中即存放有A类型对象,又存放有B类型对象,如果用户将A对象和B对象类型弄混淆,则容易产生转换错误,会发生类型转换异常。

b.  如果用户不知道集合容器中元素的数据类型,同样也可能会产生类型转换异常。

鉴于上述的问题,java5中引入了泛型机制,在定义集合容器对象时显式指定其元素的数据类型,在使用集合容器时,编译器会检查数据类型是否和容器指定的数据类型相符合,如果不符合在无法编译通过,从编译器层面强制保证数据类型安全。

 

(1).java常用集合容器泛型使用方法:

如:

public class New{  
    public static <K, V> Map<K, V> map(){  
        return new HashMap<K, V>();  
}  
public static <T> List<T> list(){  
    return new ArrayList<T>() ;  
}  
public static <T> LinkedList<T> lList(){  
    return new LinkedList<T>();  
}  
public static <T> Set<T> set(){  
    return new HashSet<T>();  
}  
public static <T> Queue<T> queue(){  
    return new LinkedList<T>() ;  
}  
;public static void main(String[] args){  
    Map<String, List<String>> sls = New.map();  
    List<String> ls = New.list();  
    LinkedList<String> lls = New.lList();  
    Set<String> ss = New.set();  
    Queue<String> qs = New.queue();  
}  
}  
 
(2).Java中的Set集合是数学上逻辑意义的集合,使用泛型可以很方便地对任何类型的Set集合进行数学运算,代码如下:
public class Sets{  
    //并集  
    public static <T> Set<T> union(Set<T> a, Set<T> b){  
        Set<T> result = new HashSet<T>(a);  
        result.addAll(b);  
        return result;  
}  
//交集  
public static <T> Set<T> intersection(Set<T> a, Set<T> b){  
    Set<T> result = new HashSet<T>(a);  
    result.retainAll(b);  
    return result;  
}  
//差集  
public static <T> Set<T> difference(Set<T> a, Set<T> b){  
    Set<T> result = new HashSet<T>(a);  
    result.removeAll(b);  
    return Result;  
}  
//补集  
public static <T> Set<T> complement(Set<T> a, Set<T> b){  
    return difference(union(a, b), intersection(a, b));  
}  
}  

 

4.泛型也可用于匿名内部类

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

	private Customer() {
	}

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

	// A method to produce Generator objects:
	public static Generator<Customer> generator() {
		//匿名内部类
		return new Generator<Customer>() {
			public Customer next() {
				return new Customer();
			}
		};
	}
}

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

	private Teller() {
	}

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

	// A single Generator object:
	public static Generator<Teller> generator = new Generator<Teller>() {
		//匿名内部类
		public Teller next() {
			return new Teller();
		}
	};
}

 

 5.用泛型构建复杂数据结构模型

  泛型能够简单而安全的创建复杂的数据结构模型,例如下面的 泛型List :

public class TupleList<A, B, C, D> extends ArrayList<FourTuple<A, B, C, D>> {
	public static void main(String[] args) {
		TupleList<Vehicle, Amphibian, String, Integer> tl = new TupleList<Vehicle, Amphibian, String, Integer>();
		tl.add(TupleTest.h());
		tl.add(TupleTest.h());
		for (FourTuple<Vehicle, Amphibian, String, Integer> i : tl)
			System.out.println(i);
	}
} /*
 * Output:
 * (75% match) (Vehicle@11b86e7, Amphibian@35ce36, hi, 47)
 * (Vehicle@757aef, Amphibian@d9f9c3, hi, 47)
 */// :~

 

尽管看起来复杂,但依旧是一个强大的数据结构.

 

6.泛型边界:

边界使得你可以在用于泛型的参数类型上设置限制条件。

Java泛型编程时,编译器忽略泛型参数的具体类型,认为使用泛型的类、方法对Object都适用,这在泛型编程中称为类型信息檫除。

例如:

class GenericType{  
    public static void main(String[] args){  
        System.out.println(new ArrayList<String>().getClass());  
        System.out.println(new ArrayList<Integer>().getClass());  
}  
}  

输出结果为:

java.util.ArrayList

java.util.ArrayList

泛型忽略了集合容器中具体的类型,这就是类型檫除

 

7.类型通配符

Box<Number>和Box<Integer>实际上都是Box类型,现在需要继续探讨一个问题,那么在逻辑上,类似于Box<Number>和Box<Integer>是否可以看成具有父子关系的泛型类型呢?

为了弄清这个问题,我们继续看下下面这个例子:

 class Box<T> {
 
     private T data;
 
     public Box() {
 
     }
 
     public Box(T data) {
         setData(data);
     }
 
     public T getData() {
         return data;
     }
 
     public void setData(T data) {
         this.data = data;
     }
 
 }

 

public class GenericTest {
 
      public static void main(String[] args) {
  
          Box<Number> name = new Box<Number>(99);
          Box<Integer> age = new Box<Integer>(712);
  
          getData(name);
          
         //The method getData(Box<Number>) in the type GenericTest is 
         //not applicable for the arguments (Box<Integer>)
         getData(age);   // 1
 
     }
     
     public static void getData(Box<Number> data){
         System.out.println("data :" + data.getData());
     }
19 
20 }

 

假设Box<Number>在逻辑上可以视为Box<Integer>的父类,那么//1和//2处将不会有错误提示了,那么问题就出来了,通过getData()方法取出数据时到底是什么类型呢?Integer? Float? 还是Number?且由于在编程过程中的顺序不可控性,导致在必要的时候必须要进行类型判断,且进行强制类型转换。显然,这与泛型的理念矛盾,因此,在逻辑上Box<Number>不能视为Box<Integer>的父类。

好,那我们回过头来继续看“类型通配符”中的第一个例子,我们知道其具体的错误提示的深层次原因了。那么如何解决呢?总部能再定义一个新的函数吧。这和Java中的多态理念显然是违背的,因此,我们需要一个在逻辑上可以用来表示同时是Box<Integer>和Box<Number>的父类的一个引用类型,由此,类型通配符应运而生。

类型通配符一般是使用 ? 代替具体的类型实参。注意了,此处是类型实参,而不是类型形参!且Box<?>在逻辑上是Box<Integer>、Box<Number>...等所有Box<具体类型实参>的父类。由此,我们依然可以定义泛型方法,来完成此类需求。

在代码//1处出现了错误提示信息:The method getData(Box<Number>) in the t ype GenericTest is not applicable for the arguments (Box<Integer>)。显然,通过提示信息,我们知道Box<Number>在逻辑上不能视为Box<Integer>的父类。那么,原因何在呢?

 

假设Box<Number>在逻辑上可以视为Box<Integer>的父类,那么//1和//2处将不会有错误提示了,那么问题就出来了,通过getData()方法取出数据时到底是什么类型呢?Integer? Float? 还是Number?且由于在编程过程中的顺序不可控性,导致在必要的时候必须要进行类型判断,且进行强制类型转换。显然,这与泛型的理念矛盾,因此,在逻辑上Box<Number>不能视为Box<Integer>的父类。

好,那我们回过头来继续看“类型通配符”中的第一个例子,我们知道其具体的错误提示的深层次原因了。那么如何解决呢?总部能再定义一个新的函数吧。这和Java中的多态理念显然是违背的,因此,我们需要一个在逻辑上可以用来表示同时是Box<Integer>和Box<Number>的父类的一个引用类型,由此,类型通配符应运而生。

类型通配符一般是使用 ? 代替具体的类型实参。注意了,此处是类型实参,而不是类型形参!且Box<?>在逻辑上是Box<Integer>、Box<Number>...等所有Box<具体类型实参>的父类。由此,我们依然可以定义泛型方法,来完成此类需求。

 

public class GenericTest {
 
      public static void main(String[] args) {
  
          Box<String> name = new Box<String>("corn");
          Box<Integer> age = new Box<Integer>(712);
          Box<Number> number = new Box<Number>(314);
  
          getData(name);
         getData(age);
         getData(number);
     }
 
     public static void getData(Box<?> data) {
         System.out.println("data :" + data.getData());
     }
 
 }

 

有时候,我们还可能听到类型通配符上限和类型通配符下限。具体有是怎么样的呢?

在上面的例子中,如果需要定义一个功能类似于getData()的方法,但对类型实参又有进一步的限制:只能是Number类及其子类。此时,需要用到类型通配符上限。

 

  public class GenericTest {
  
      public static void main(String[] args) {
  
          Box<String> name = new Box<String>("corn");
          Box<Integer> age = new Box<Integer>(712);
          Box<Number> number = new Box<Number>(314);
  
          getData(name);
         getData(age);
         getData(number);
         
         //getUpperNumberData(name); // 1
         getUpperNumberData(age);    // 2
         getUpperNumberData(number); // 3
     }
 
     public static void getData(Box<?> data) {
         System.out.println("data :" + data.getData());
     }
     
     public static void getUpperNumberData(Box<? extends Number> data){
         System.out.println("data :" + data.getData());
     }
 
 }

 

此时,显然,在代码//1处调用将出现错误提示,而//2 //3处调用正常。

类型通配符上限通过形如Box<? extends Number>形式定义,相对应的,类型通配符下限为Box<? super Number>形式,其含义与类型通配符上限正好相反,在此不作过多阐述了。

 

另外

Java中没有所谓的泛型数组一说。

对于泛型,最主要的还是需要理解其背后的思想和目的。

 阅读文章全部内容  
点击查看
文章点评
相关文章
白诗秀儿 关注

文章收藏:1308

TA的最新收藏