今天我们来看看java的泛型吧,之前总是听见老师说泛型泛型,感觉就是在使用的时候才能确定类型的函数或者方法吧,这里我写了一个两个泛型,一个是自定义的类的泛型,还有一个是方法,大家看看吧,我感觉只要知道泛型放的位置,在函数里面就可以随便使用这个泛型了,或许在这里或者你看了代码以后会想到c++的模板,但是我想说的是这个和c++的模板只是看起来相似,c++的模板每个类型都会对应一个代码,而java中无论你多少中类型都只会有一种代码,贴代码:
package www.jk.genericdemo;
public class Test {
public static void main(String[] args) {
//we will define the actually type when we use it
KeyValuePair<String, Integer> kvp=new KeyValuePair<String, Integer>();
kvp.put("name",1);
System.out.println(kvp.getValue("name"));
show("1341");
}
public static <E> void show(E e){
E value;
value=e;
System.out.println(value);
}
}
class KeyValuePair<Key,Value>{
Key key;
Value value;
public void put(Key key,Value value) {
this.key=key;
this.value=value;
}
public Value getValue(Key key) {
if(this.key.equals(key)){
//if the key is the same as the saved key,we will return the value
return this.value;
}else{
return null;
}
}
}