文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>泛型

泛型

时间:2011-04-24  来源:情定诺坎普

Junit测试的方法没有参数 没有返回值 必须的

泛型:使用泛型可以避免类型的强制转换  1.5版本出现的安全机制 将运行时期出现的的问题转移到了编译时期

什么时候使用泛型类呢:当类名操作的引用数据类型不确定的时候 就可以使用泛型

泛型可以定义到类上 class Tool <Q> 更可以定义到方法上 public <Q>void show 方法泛型 通常情况下静态居多

泛型限定:

?代表通配类型

泛型编译后生产的class文件 不再包含泛型

泛形的基本术语,以ArrayList<E>为例:<>念着typeof

ArrayList<E>中的E称为类型参数变量

ArrayList<Integer>中的Integer称为实际类型参数

整个称为ArrayList<E>泛型类型

整个ArrayList<Integer>称为参数化的类型ParameterizedType

使用泛型的时候 如果都使用到泛型 两边必一致  如果只用一边 是可以 的

自定义泛型 避免 强转

public <T> T a (T t ) {

} 有几个参数就要用到几个

可以把泛型定义到类上 作用到整个类上 对静态成员是无效的

public class Demo5<T, E, K> {

 

    // 自定义类上的泛形

 

    public void testa() {

       // Demo6 d = new Demo6<String, String, String>();

       a("aaa");

    }

 

    public <T> T a(T t) {

 

       return null;

    }

 

    public void b(T t, E e, K k) {

 

    }

 

    public static <T> void c(T t) {

 

    }

 

}

//用泛型定义一个方法 是数组逆置

package cn.itcast.collections;

 

import org.junit.Test;

 

public class Demo6 {

   

    Integer arr[] = {1,2,3,4,5};

   

    @Test

    public void test(){

       reverse(arr);

       for(int i : arr) {

           System.out.print(i + " ");

       }

    }

   

    public <T> void swap (T arr[] , int pos1 , int pos2) {

       T temp = arr[pos1];

       arr[pos1] = arr[pos2];

       arr[pos2] = temp ;

    }

   

    public <T> void reverse( T arr[]  ) {

       int start = 0 ;

       int end = arr.length - 1 ;

      

       while(true){

           if(start>=end){

              break;

           }

          

           T temp = arr[start];

           arr[start] = arr[end];

           arr[end] = temp;

          

           start++;

           end--;

       }

      

    }

   

}

相关阅读 更多 +
排行榜 更多 +
地狱摩托游戏最新版下载

地狱摩托游戏最新版下载

赛车竞速 下载
小猫快来钓鱼游戏下载

小猫快来钓鱼游戏下载

休闲益智 下载
殴打氪金大佬昊天手游下载

殴打氪金大佬昊天手游下载

休闲益智 下载