麻烦些个java泛型类的小程序给我看下,是自定义的哦,我是初学者,可不可以是那种不是很长的,程序整个结构比较清晰的那种给我看下,谢谢
要快!!
楼主要的是自定义的泛型类,楼上的怎么都是人家jdk自带的啊!
我的代码
public class JavaBean<K> {
private String userName = "";
private String passWord = "";
private int age = 0;
private K k = null;
public JavaBean(){
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(int age) {
this.age = age;
}
/**
* @return the passWord
*/
public String getPassWord() {
return passWord;
}
/**
* @param passWord the passWord to set
*/
public void setPassWord(String passWord) {
this.passWord = passWord;
}
/**
* @return the userName
*/
public String getUserName() {
return userName;
}
/**
* @param userName the userName to set
*/
public void setUserName(String userName) {
this.userName = userName;
}
public K getString(){
return k;
}
/**
* @param k the k to set
*/
public void setK(K k) {
this.k = k;
}
}
---------------------test
public class TestMain {
public static void main(String[] args) {
JavaBean<Integer> bean2 = new JavaBean<Integer>();
bean2.setK(3);
JavaBean<String> bean1 = new JavaBean<String>();
bean1.setK("hello");
}
}
我的代码
public class JavaBean<K> {
private String userName = "";
private String passWord = "";
private int age = 0;
private K k = null;
public JavaBean(){
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(int age) {
this.age = age;
}
/**
* @return the passWord
*/
public String getPassWord() {
return passWord;
}
/**
* @param passWord the passWord to set
*/
public void setPassWord(String passWord) {
this.passWord = passWord;
}
/**
* @return the userName
*/
public String getUserName() {
return userName;
}
/**
* @param userName the userName to set
*/
public void setUserName(String userName) {
this.userName = userName;
}
public K getString(){
return k;
}
/**
* @param k the k to set
*/
public void setK(K k) {
this.k = k;
}
}
---------------------test
public class TestMain {
public static void main(String[] args) {
JavaBean<Integer> bean2 = new JavaBean<Integer>();
bean2.setK(3);
JavaBean<String> bean1 = new JavaBean<String>();
bean1.setK("hello");
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答 2009-06-29
java.util包中的很多集合类都会用泛型编程
比如常见的ArrayList
定义一个ArrayList<T> array = new ArrayList<T>();
这里T就可以用任何类型来代替
比如 ArrayList<String> array = new ArrayList<String>();
这时候ArrayList中存的就是String类型的元素了
比如常见的ArrayList
定义一个ArrayList<T> array = new ArrayList<T>();
这里T就可以用任何类型来代替
比如 ArrayList<String> array = new ArrayList<String>();
这时候ArrayList中存的就是String类型的元素了
第2个回答 2009-06-29
List<String> list=new List();
list.add("absd");
list.add(123);//将会报错
List list1=new List();
list.add(123);
list.add("123");//正确
定义其类型只能往LIST里添加字符串;
若添加整形数字 就回出错.
list.add("absd");
list.add(123);//将会报错
List list1=new List();
list.add(123);
list.add("123");//正确
定义其类型只能往LIST里添加字符串;
若添加整形数字 就回出错.