Java笔记-范型使用

定义范型类:
package shdemo;

import hibernatemap.User;
import java.util.ArrayList;
import java.util.List;


public class Fan {
private T value;

public T getValue() {
return value;
}

public void setValue(T value) {
this.value = value;
}

}
//T可以未任意指定类型.
测试类testdemo
public class testdemo {

public static void main (String[] args) {
Fan fan = new Fan();//限制了T为String类型
fan.setValue("This is a Generics testing");
System.out.println(fan.getValue());
User user = new User();
user.setId("1234");
user.setName("daniel");
user.setAge(22);
User user1 = new User();
user1.setId("12345");
user1.setName("Jason");
user1.setAge(22);
Fan fanuser = new Fan;//限制了T为User类型
fanuser.setValue(user);
List userlist = new ArrayList();//List默认范型,现在限制userlist类型为User;
for(User u : userList){
System.out.println(u.getUsername());
}
}

你可能感兴趣的:(JDK)