简单泛型运用_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > 简单泛型运用

简单泛型运用

 2013/8/30 16:09:21  QuarterLifeForJava  程序员俱乐部  我要评论(0)
  • 摘要:User实体类packagetest;publicclassUser{privateStringuname;privateintuage;privateStringclassName;publicStringgetUname(){returnuname;}publicvoidsetUname(Stringuname){this.uname=uname;}publicintgetUage(){returnuage;}publicvoidsetUage(intuage){this
  • 标签:运用 泛型
User实体类
class="java" name="code">
package test;
public class User {
	private String uname;
	private int uage;
	private String className;
	public String getUname() {
		return uname;
	}
	public void setUname(String uname) {
		this.uname = uname;
	}
	public int getUage() {
		return uage;
	}
	public void setUage(int uage) {
		this.uage = uage;
	}
	public String getClassName() {
		return className;
	}
	public void setClassName(String className) {
		this.className = className;
	}
	public User(String uname, int uage, String className) {
		super();
		this.uname = uname;
		this.uage = uage;
		this.className = className;
	}
	public User() {
		super();
	}
}

Teacher实体类
package test;
public class Teacher {
	private String tname;
	private int tage;
	public String getTname() {
		return tname;
	}
	public void setTname(String tname) {
		this.tname = tname;
	}
	public int getTage() {
		return tage;
	}
	public void setTage(int tage) {
		this.tage = tage;
	}
	public Teacher(String tname, int tage) {
		super();
		this.tname = tname;
		this.tage = tage;
	}
	public Teacher() {
		super();
	}
}

简单泛型
package test;
import java.util.List;
/**
 * 泛型类
 * @param <T>
 */
public class FanXing<T> {
	//简单迭代的输出
	public void printSomthing(List<T> list){
		for(int i=0;i<list.size();i++){
			System.out.println(list.get(i));
		}
	}
}

简单测试下
package test;
import java.util.ArrayList;
import java.util.List;
public class Test {	
	public static void main(String[] args) {
		//新建3个User对象
		User u = new User("张三",12,"二班");
		User u1 = new User("李四",13,"三班");
		User u2 = new User("王五",14,"四班");
		//把3个User对象放到集合中去
		List<User> list = new ArrayList<User>();
		list.add(u);
		list.add(u1);
		list.add(u2);
		//新建3个Teacher对象
		Teacher t = new Teacher("汪老师",34);
		Teacher t1 = new Teacher("李老师",38);
		Teacher t2 = new Teacher("洪老师",39);
		//把3个Teacher对象放到集合中去
		List<Teacher> lista = new ArrayList<Teacher>();
		lista.add(t);
		lista.add(t1);
		lista.add(t2);
		//迭代User
		FanXing<User> fx = new FanXing<User>();
		fx.printSomthing(list);
		//迭代Teacher
		new FanXing<Teacher>().printSomthing(lista);
	}
}
上一篇: JAVA MD5 加密常用 方法 下一篇: 没有下一篇了!
发表评论
用户名: 匿名