1 认识泛型:
案例代码
package csdn.zyl.demo;
class Point{
private Object x;
private Object y;
public Object getX() {
return x;
}
public void setX(Object x) {
this.x = x;
}
public Object getY() {
return y;
}
public void setY(Object y) {
this.y = y;
}
}
/*
* 经纬度
* int
* float
* String 类型
*/
public class GenericalDemo01 {
class Point{
private Object x;
private Object y;
public Object getX() {
return x;
}
public void setX(Object x) {
this.x = x;
}
public Object getY() {
return y;
}
public void setY(Object y) {
this.y = y;
}
}
/*
* 经纬度
* int
* float
* String 类型
*/
public class GenericalDemo01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Point<String> point = new Point<String>();
point.setX("精度为:109");
point.setY("精度为:109");
// Point p = new Point();
// p.setX(10.1f);
// p.setY(10.1f);
// Float px = (Float)p.getX();
// Float py = (Float)p.getY();
System.out.println(point.getX()+" "+point.getY());
}
// TODO Auto-generated method stub
Point<String> point = new Point<String>();
point.setX("精度为:109");
point.setY("精度为:109");
// Point p = new Point();
// p.setX(10.1f);
// p.setY(10.1f);
// Float px = (Float)p.getX();
// Float py = (Float)p.getY();
System.out.println(point.getX()+" "+point.getY());
}
}
2 以及泛型的构造方法
代码案例如下:
package csdn.zyl.demo;
class Con<T>{
private T value;
public Con(T value)
{
this.value = value;
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
}
public class GenericDemo02 {
class Con<T>{
private T value;
public Con(T value)
{
this.value = value;
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
}
public class GenericDemo02 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Con<String> con = new Con<String>("构造方法中使用泛型");
System.out.println(con.getValue());
}
// TODO Auto-generated method stub
Con<String> con = new Con<String>("构造方法中使用泛型");
System.out.println(con.getValue());
}
}
3 设置多个泛型:
package csdn.zyl.demo;
/*
* 指定多个泛型
*/
class Gen<K,T>{
private T take;
private K key;
public T getTake() {
return take;
}
public void setTake(T take) {
this.take = take;
}
public K getKey() {
return key;
}
public void setKey(K key) {
this.key = key;
}
}
public class GenericalDemo04 {
public static void main(String[] args)
{
Gen<String,Integer> gen = new Gen<String,Integer>();
gen.setTake(10);
gen.setKey("key");
System.out.println(gen.getTake()+" "+gen.getKey());
}
}
案例结果:10 key
4 通配符:
5 泛型接口