15.3 泛型接口

泛型也可以用于接口, 下面显示了一个随机Robot访问器的示例, 实现了一个自定义的Generator泛型接口

package com.cnsuning.src;

import java.lang.reflect.*;
import java.util.*;

public class Main {

	public static void main(String[] args) {
		RobotGenerator rg = new RobotGenerator();
		for(Robot robot: rg){
			System.out.println(robot);
		}
	}
}

class Robot {
	private static int count = 0;
	private int id = count++;
	public String toString(){
		return this.getClass().getSimpleName()+" "+id;
	}
}

class T100 extends Robot{
	
}

class Gundam extends Robot{
	
}

class Freedom extends Gundam{
	
}

class Striker extends Gundam{
	
}

class Zaku extends Robot{
	
}

interface IGenerator<T>{
	T next();
}

class RobotGenerator implements IGenerator<Robot>,Iterable<Robot>{
	private List<Class<? extends Robot>> classTypes = new LinkedList<Class<? extends Robot>>();
	{
		classTypes.add(Robot.class);
		classTypes.add(T100.class);
		classTypes.add(Gundam.class);
		classTypes.add(Freedom.class);
		classTypes.add(Striker.class);
		classTypes.add(Zaku.class);
	}
	private Random rand= new Random(47);
	private int maxLimit = 10;
	RobotGenerator(){
		
	}
	@Override
	public Robot next() {
		int randIndex = rand.nextInt(classTypes.size());
		try {
			Robot randRobot = classTypes.get(randIndex).newInstance();
			return randRobot;
		} catch (InstantiationException | IllegalAccessException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
	}
	@Override
	public Iterator<Robot> iterator() {
		// TODO Auto-generated method stub
		return new RobotIterator();
	}
	private class RobotIterator implements Iterator<Robot>{
		int count = maxLimit;
		@Override
		public boolean hasNext() {
			return count>0;
		}

		@Override
		public Robot next() {
			count--;
			return RobotGenerator.this.next();
		}

		@Override
		public void remove() {
			// TODO Auto-generated method stub
			throw new RuntimeException();
		}
		
	}
}

测试结果:

Gundam 0
Zaku 1
T100 2
Zaku 3
T100 4
Zaku 5
Striker 6
Gundam 7
Robot 8
T100 9

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值