2、泛型的问题:

定义:指的是把复杂的类型变成唯一性,必须是类或者自定义的类型;<类型>

常见的方法有四种:

第一:可以使用来表示任意一种类型,只要主方法里面给它类型即可;

第二:泛型可以继承;,此时在方法里面给定的类型之后就不能变了;

第三:通配符;,此时在主方法里面可以给定任意一种超级接口下的实现类;

第四:泛型的方法;必须有无返回值的前面加;           例子:public   void f(T x){}

 常调用的方法:System.out.println(x.getClass().getName());

注意事项:记得对象不要搞错!






第一种:

public class Book

//第一种:初试泛型

private T x;

public Book(T x){

this.x=x;

}


public T getX() {

return x;

}


public void setX(T x) {

this.x = x;

}

public void f(){

System.out.println(x.getClass().getName());

}


public static void main(String[] args) {

Book i=new Book(12);

i.f();

int j=i.getX();

System.out.println(j);

Book s=new Book("hello world");

s.f();


}


}

第二种:

public class Test {

private T x;

Test(T x){

this.x=x;

}


public T getX() {

return x;

}



public void setX(T x) {

this.x = x;

}

     public void f(){

    System.out.println(x.getClass().getName());

     }


public static void main(String[] args) {

Test t=new Test(new ArrayList());

ArrayList list=new ArrayList();

list.add(12);

t.setX(list);

System.out.println(t.getX());

}

}

第三种:

public class Test1 {


//泛型里面可以有继承:

private T x;

public Test1(T x){

this.x=x;

}

public T getX() {

return x;

}


public void setX(T x) {

this.x = x;

}


public static void main(String[] args) {

//第三种:通配符?:

@SuppressWarnings("rawtypes")

Test1 list=null;

list=new Test1(new LinkedList());

System.out.println(list.getClass().getName());


}


}

第四种:

public class Test2 {

   //第四种:泛型的方法:必须在有无返回值前面加上类型;

public void f(T x){

System.out.println(x.getClass().getName());

}

public static void main(String[] args) {

Test2 t=new Test2();

t.f("");

t.f(12);

t.f('a');

t.f(true);

}

}