Strict output behavior like Collections.emptyList () and / or common Java methods?

This is jdk1.7.0_04.

I tried to use Collections.emptyList()instead new, using my own empty list in a conditional expression:

List<String> list = (anArray != null) ? Arrays.asList(anArray) : Collections.emptyList();

but get the following error:

error: incompatible types
        List<String> list = (anArray != null) ? Arrays.asList(anArray) : Collections.emptyList();
                                              ^
  required: List<String>
  found:    List<CAP#1>
  where CAP#1 is a fresh type-variable:
    CAP#1 extends Object from capture of ? extends Object
1 error

I was able to understand that I need to change things:

List<String> list = (anArray != null) ? Arrays.asList(anArray) : Collections.<String>emptyList();

But as part of the work on this, I came across a bizarre (to me, anyway) situation that:

List<String> alwaysEmpty = Collections.emptyList();

compiles fine, but:

List<String> alwaysEmpty = (List<String>) Collections.emptyList();

gives the following compilation error:

error: inconvertible types
        List<String> alwaysEmpty = (List<String>) Collections.emptyList();
                                                                       ^
  required: List<String>
  found:    List<Object>

What the hell?

Now I understand that, for some strange reason, using a conditional operator somehow blocks the type inference system from implementing what the type parameter emptyList()should be for the call String, and therefore it must be explicitly specified. But why is (admittedly, excessive) pretense added?

+5
2

( , ) ?

Collections.emptyList() - - ? :

// Redundant here, but just as an example
List<String> alwaysEmpty = Collections.<String>emptyList();

:

public static void main(String[] args) {              
    List<String> list = (args != null)
        ? Arrays.asList(args) : Collections.<String>emptyList();
}
+9

, , - SO. , Sun/Oracle . , , , . :

, , , LHS (List<String> ). : JLS, :

" (Β§5.1.10) lub(T1, T2) (Β§15.12.2.7)."

, lub. :

class A {}
class B extends A{}
class C extends A{}
class Foo<X> 
Foo<? extends A> l = b ? new Foo<B>() : new Foo<C>()

, LHS Foo<? extends A>, RHS lub(Foo<B>, Foo<C>), Foo<? extends B&C>.

+5

All Articles