有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

用泛型实现数组的java转换

以下陈述之间有什么区别:

List<E>[] x = (List<E>[]) new List[100];

List<E>[] x = new List[100];

在我的脚本中,注意到前者是创建泛型数组的正确方法(尽管它会导致编译器警告)。但是我不太明白(List<E>[])语句有什么用List<E>[]甚至不是它自己的类型,编译器只需将其替换为(List[]),因此

List<E>[] x = (List[]) new List[100];

List[]List[]的转换,这是无用的。那么,为什么要把(List<E>[])放在第一位呢


共 (3) 个答案

  1. # 1 楼答案

    与泛型一样,存储在任何集合中的对象类型将在添加到集合时进行类型检查。主要通过泛型,代码可以被不需要了解泛型的其他人理解。因此,通过在编译时插入检查并在运行时擦除,可以实现这种行为

    您可以看到:http://docs.oracle.com/javase/tutorial/java/generics/

  2. # 2 楼答案

    Generics add stability to your code by making more of your bugs detectable at compile time.

    这是我给出的链接的一部分,我认为这很重要,所以我在这里发布

    This is a small excerpt from the definitions of the interfaces List and Iterator in package java.util:

    public interface List <E> {
        void add(E x);
        Iterator<E> iterator();
    }
    
    public interface Iterator<E> {
        E next();
        boolean hasNext();
    }
    

    This code should all be familiar, except for the stuff in angle brackets. Those are the declarations of the formal type parameters of the interfaces List and Iterator.

    Type parameters can be used throughout the generic declaration, pretty much where you would use ordinary types.

    We know the invocations of the generic type declaration List, such as List. In the invocation (usually called a parameterized type), all occurrences of the formal type parameter (E in this case) are replaced by the actual type argument (in this case, Integer).

    You might imagine that List stands for a version of List where E has been uniformly replaced by Integer:

    public interface IntegerList {
            void add(Integer x);
            Iterator<Integer> iterator();
        }
    

    这种直觉可能会有所帮助,但也会误导人

    这很有帮助,因为参数化类型列表 确实有一些方法看起来就像这个扩展

    这是一种误导,因为泛型的声明永远不会被接受 实际上是这样扩展的。没有多个副本 代码不在源代码中,不在二进制代码中,不在磁盘上,也不在内存中

    A generic type declaration is compiled once and for all, and turned into a single class file, just like an ordinary class or interface declaration.

    Type parameters are analogous to the ordinary parameters used in methods or constructors. Much like a method has formal value parameters that describe the kinds of values it operates on, a generic declaration has formal type parameters. When a method is invoked, actual arguments are substituted for the formal parameters, and the method body is evaluated.

    调用泛型声明时 实际类型参数将替换为形式类型参数。这就是>;仿制药的重要性

    你可以在这里寻找more information about Generics

  3. # 3 楼答案

    这:

    List<E>[] x = new List[100];
    

    表示x是数组类型。该数组的元素是可以容纳类型E对象的列表。您正在为它分配一组列表,这些列表可以容纳任何对象

    下一项声明:

    List<E>[] x = (List<E>[]) new List[100];
    

    情况也没有好转。选角没用。缺陷仍然是一样的

    最终,所有这些都是这样做的借口:

    List<E>[] x =  new List<E>[100];
    

    Java中不允许使用泛型和数组。因为数组在运行时保留其元素类型,而泛型构造则不保留。不能存在元素类型未严格定义的数组

    问题是由于定义了引用类型List<E>[],根据定义,该类型不允许在Java中实例化。因此,避免使用此类类型

    你可以选择一个列表作为替代