Java 1.6:创建一个List< T>的数组 [英] Java 1.6: Creating an array of List<T>

查看:92
本文介绍了Java 1.6:创建一个List< T>的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我不能创建一个List数组?

  List< String> [] nav = new List< String> ; [] {new ArrayList< String>()}; 

Eclipse表示无法创建List的通用数组

  ArrayList< String> [] nav = new ArrayList< String> [] {new ArrayList< String> ;()}; 

Eclipse表示无法创建ArrayList的通用数组

  List< String> [] getListsOfStrings(){
List< String> groupA = new ArrayList< String>();
列表< String> groupB = new ArrayList< String>();
返回新的列表< String> [] {groupA,groupB};
}

但我可以这样做:

  List [] getLists(){
return new List [] {new ArrayList(),new ArrayList()};

$ / code>

Eclipse表示List和ArrayList是原始类型但它编译...



看起来很简单,为什么它不起作用?

解决方案

好的,泛型教程会给出


数组对象
的组件类型可能不是类型变量或
参数化类型,除非它是
(无界)通配符类型。您可以
声明数组类型,其元素类型
是类型变量或参数化
类型,但不是数组对象



这是
令人讨厌的,可以肯定。这个限制
是避免这种情况的必要条件:

  //不是真的允许。 
List< String> [] lsa =新列表< String> [10];
Object o = lsa;
Object [] oa =(Object [])o;
列表<整数> li = new ArrayList< Integer>();
li.add(new Integer(3));
//不确定,但通过运行时存储检查
oa [1] = li;

//运行时错误:ClassCastException。
String s = lsa [1] .get(0);

如果参数化类型的数组允许
,则前面的示例将
编译没有任何未经检查的
警告,但在运行时失败。
我们已经将类型安全作为泛型的主要
设计目标。



Why can't I create an array of List ?

List<String>[] nav = new List<String>[] { new ArrayList<String>() };

Eclipse says "Cannot create a generic array of List"

or

ArrayList<String>[] nav = new ArrayList<String>[] { new ArrayList<String>() };

Eclipse says "Cannot create a generic array of ArrayList"

or

List<String>[] getListsOfStrings() {
    List<String> groupA = new ArrayList<String>();
    List<String> groupB = new ArrayList<String>();
    return new List<String>[] { groupA, groupB };
}

But I can do this:

List[] getLists() {
    return new List[] { new ArrayList(), new ArrayList() };
}

Eclipse says that List and ArrayList are raw types but it compiles...

Seems pretty simple, why won't it work?

解决方案

Well, generics tutorial give the answer to your question.

The component type of an array object may not be a type variable or a parameterized type, unless it is an (unbounded) wildcard type.You can declare array types whose element type is a type variable or a parameterized type, but not array objects.

This is annoying, to be sure. This restriction is necessary to avoid situations like:

// Not really allowed.
List<String>[] lsa = new List<String>[10];
Object o = lsa;
Object[] oa = (Object[]) o;
List<Integer> li = new ArrayList<Integer>();
li.add(new Integer(3));
// Unsound, but passes run time store check
oa[1] = li;

// Run-time error: ClassCastException.
String s = lsa[1].get(0);

If arrays of parameterized type were allowed, the previous example would compile without any unchecked warnings, and yet fail at run-time. We've had type-safety as a primary design goal of generics.

这篇关于Java 1.6:创建一个List&lt; T&gt;的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆