Java 泛型举例

Java 5 之后引入泛型(Genetics)。

使用泛型的入门例子:
package generics;

import java.util.*;

public class Eg01 {
	public static void main(String[] args){
		List<Integer> myIntList = new LinkedList<Integer>(); 
		myIntList.add(new Integer(0));
		Integer x = myIntList.iterator().next(); // 3
		System.out.println(x);
	}

}


解释:因为使用泛型语法,// 3  处不必进行Integer类型强制转换。

泛型的简单定义:
package generics.define;

public interface List<E> {
	void add(E x);
	Iterator<E> iterator();
}
interface Iterator<E> {
	E next();
	boolean hasNext();
}



有边界的通配符:
package generics.boundedwildcards;
import java.util.*;

public class Census{
	public static void addRegistry(Map<String, ? extends Person> registry){
	}
	public static void main(String[] args){
		Map<String, Driver> allDrivers = new HashMap<String, Driver>();
		Census.addRegistry(allDrivers);
	}
}

class Driver extends Person{
	
}

class Person{
	
}

===========================================================
package generics.boundedwildcards;

public abstract class Shape{
	public abstract void draw(Canvas c);
	
}




package generics.boundedwildcards;

public class Circle extends Shape{
	private int x, y, radius;
	public void draw(Canvas c){
		
	}
}

package generics.boundedwildcards;

public class Rectangle extends Shape{
	private int x, y, width, height;
	public void draw(Canvas c){
		
	}
}

package generics.boundedwildcards;

import java.util.List;

public class Canvas {
	public void draw(Shape s){
		s.draw(this);
	}
	//public void drawAll(List<Shape> shapes){
	public void drawAll(List<? extends Shape> shapes){
		for(Shape s : shapes){
			s.draw(this);
		}
		
	}
}


你可能感兴趣的:(java,C++,c,C#)