Loading

Java中泛型数组的使用

package com.srie.testjava;

import java.util.ArrayList;
import java.util.List;

public class TestClassDefine3<T, S extends T> {

    public static void main(String[] args) {

        // 这个会有warning;
        TestClassDefine3<String, String>[] tcd3 = new TestClassDefine3[12];
        TestClassDefine3<Integer, Integer> t1i = new TestClassDefine3<Integer, Integer>();
        TestClassDefine3<String, String> t2s = new TestClassDefine3<String, String>();
        // tcd3[0] = t1i; // 这个类型不匹配,会有编译错误;
        tcd3[0] = t2s; // 这个可以添加;

        List<String> slist = new ArrayList<String>();
        slist.add("a");
        slist.add("b");
        @SuppressWarnings("unchecked")
        List<String>[] sListArr = new ArrayList[12];
        sListArr[0] = slist;
        // System.out.println(sListArr);
        for (List<String> list : sListArr) {
            if (list != null) {
                for (String string : list) {
                    System.out.println(string);
                }
            }
        }

    }

}

 反编译之后的结果:

package com.srie.testjava;

import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class TestClassDefine3<T, S extends T>
{
  public static void main(String[] args)
  {
    List[] arrayOfList1;
    TestClassDefine3[] tcd3 = new TestClassDefine3[12];
    TestClassDefine3 t1i = new TestClassDefine3();
    TestClassDefine3 t2s = new TestClassDefine3();

    tcd3[0] = t2s;

    List slist = new ArrayList();
    slist.add("a");
    slist.add("b");

    List[] sListArr = new ArrayList[12];
    sListArr[0] = slist;

    int j = (arrayOfList1 = sListArr).length; for (int i = 0; i < j; ++i) { List list = arrayOfList1[i];
      if (list != null)
        for (Iterator localIterator = list.iterator(); localIterator.hasNext(); ) { String string = (String)localIterator.next();
          System.out.println(string);
        }
    }
  }
}

 

posted @ 2015-09-16 11:39  stono  阅读(788)  评论(0编辑  收藏  举报