范型

2017-01-13  本文已影响15人  我该忘了我自己w_u

范型就是不指定类型,用的时候在指定类型
<T,K>
使用场景

public static class Point<T> {   
 private T x;   
 private T y;  
 public T getX() {  
      return x; 
   } 
 public T getY() {  
      return y;    
   }    
 public void setX(T x) {   
      this.x = x;
   }  
 public void setY(T y) {    
      this.y = y;
   }
}
Point<String>p = new Point<String>();
p.setX("jingdu :109");
p.setY("weidu: 110");
System.out.println("x="+ p.getX()+" y="+p.getY());

用在构造函数中

class Con<T>{  
  public T value;  
  public Con (T value){    
    this.value = value;  
  }  
  public T getValue(){     
   return value;  
  }   
  public void setValue(T value){   
     this.value = value;    
  }
}

Con con = new Con<String>("构造方法中使用范性") ;
System.out.println(con.getValue());


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;
    }
}

Gen<String,Integer>g = new Gen<String, Integer>();
g.setTake(10);
g.setKey("jjjjjj");
System.out.println(g.getTake()+g.getKey());



class Info<T>{
    private T key;
    public T getKey() {
        return key;
    }
    public void setKey(T key) {
        this.key = key;
    }
    @Override
    public String toString() {
        return this.getKey().toString();
    }
}

public static void tell(Info<?> i){
    System.out.println(i);
}
Info<String>i = new Info<String>();
i.setKey("jjjjj");
tell(i);


interface GenInter<T>{
    public void say();
}
class Gin implements GenInter<String>{
    private String info;
    public Gin(String info) {
        this.info = info;
    }
    public String getInfo() {
        return info;
    }
    public void setInfo(String info) {
        this.info = info;
    }
    @Override
    public void say() {
    }

Gin g = new Gin("jkdjdkja");
System.out.println(g.getInfo());

class Gener{
    public <T>T tell(T t){
        return t;
    }
}
Gener g = new Gener();
String str = g.tell("kjlj;");
System.out.println(g.tell(str));
int i = g.tell(1);
System.out.println(g.tell(i));



public static <T>void tell(T arr[]){
    for (int i = 0; i <arr.length; i++){
        System.out.println(arr[i]);
    }
}
String arr[]={"23","23432","ddf"};
tell(arr);
上一篇下一篇

猜你喜欢

热点阅读