package test;
public class Fangxingtest3 {
public static void main(String[] args) {
String str[] = {"faker","uzi","jacklove"};//对象数组,直接实例化
Generics<String> tist = new SomethingGenerics<String>(str); //调用子类实现接口实例化,创建泛型对象
while(true){//遍历,将泛型对象中的元素输出
String s = tist.next();
if(s!=null)
System.out.print(s+" ");
else
break;
}
System.out.println();
Integer num[] = {123,-453,5345};//
Generics<Integer> numGen = new SomethingGenerics<Integer>(num);
while(true){
Integer i =numGen.next();
if(i!=null)
System.out.print(i+" ");
else
break;
}
System.out.println();
}
}
interface Generics<T>{ //泛型接口
public T next();
}
class SomethingGenerics<T> implements Generics<T>{//泛型类实现泛型接口
private T something[];//泛型域
int cursor;//游标,标识something中的当前元素
public SomethingGenerics(T something[]){//构造方法
this.something = something;
}
public T next(){//获取游标处的元素,实现接口的方法
if(cursor < something.length)
return (T) something[cursor++];
else
return null;//超出范围则返回空
}
}
运行结果:
faker uzi jacklove
123 -453 5345