有 Java 编程相关的问题?

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


共 (4) 个答案

  1. # 1 楼答案

    虽然很容易将?视为表示“任何”或“所有”类型,但它实际上指定了一个未知的单一类型。如果它真的是“任何”,你会期望它能起作用:

    List<?> l = ...
    l.add("foo");
    l.add(new Date())
    

    但事实并非如此。这是因为此代码中不知道类型,因此编译器无法判断是否应允许您向其添加任何内容

  2. # 2 楼答案

    <?>语法是java指定泛型类型为“unbounded”的方式,即它可以是“任何东西”

    Enumeration<?>是具有“无界类型”的枚举-您可以将任何类型的枚举分配给此类变量,例如:

    Vector<String> v = new Vector<String>();
    Enumeration<String> es = v.elements();
    Enumeration<?> e = es; // This assignment compiles OK
    

    但是,由于没有边界,返回类型为Object(即使它实际上是一个Enumeration<String>)的Enumeration<?>的nextElement()方法可能必须强制转换:

    String s = (String)e.nextElement(); // Unsafe cast - compiler warning
    


    在后台,Enumeration是一个类型化接口,有两个方法hasMoreElements()nextElement()。这是一次早期(糟糕的)尝试,被IterableIterator取代。一些旧类使用它,比如VectorStringTokenizer

  3. # 3 楼答案

    问号表示它代表所有类型。这里有一个example

    In addition to concrete instantiation there so-called wildcard instantiations . They do not have concrete types as type arguments, but so-called wildcards . A wildcard is a syntactic construct with a " ? " that denotes not just one type, but a family of types. In its simplest form a wildcard is just a question mark and stands for "all types".

    Example (of a wildcard parameterized type):

    public void printPair( Pair<?,?> pair) {   
    System.out.println("("+pair.getFirst()+","+pair.getSecond()+")");
    }
    
    Pair<?,?> limit = new Pair<String,Long> ("maximum",1024L); 
    printPair(limit);
    
  4. # 4 楼答案

    ??是通配符。你可以把它表示为?扩展具有相同效果的对象或类似对象。据我所知,到目前为止,通配符在java中并不完全是一门艺术,它们需要有一定的边界,但请不要引用我的话