Java Generics Capture List<?>

前端 未结 3 1749
孤独总比滥情好
孤独总比滥情好 2021-01-13 11:48

I was looking at the Java Generics documentation and found this piece of code,

public class WildcardError {

void foo(List l) {
    //This give a co         


        
3条回答
  •  梦谈多话
    2021-01-13 12:01

    In your specific case, you can explicitly fix this:

    public class WildcardError {
         void foo(List l) {
            // This will work
            l.set(0, l.get(0));
        }
    }
    

    Or if you don't want to change the original API, introduce a delegate helper method:

    public class WildcardError {
        void foo(List l) {
            foo0(l);
        }
    
        private  void foo0(List l) {
            // This will work
            l.set(0, l.get(0));
        }
    }
    

    Unfortunately, the compiler cannot infer that "obvious" type. I've been wondering about that, too. It seems like something that could be improved in a compiler, as every wild card can be informally translated to an unknown type. Probably, there are some reasons why this was omitted, perhaps this is only intuition, but formally impossible.

    UPDATE:

    Note, I've just seen this peculiar implementation of Collections.swap():

    public static void swap(List list, int i, int j) {
        final List l = list;
        l.set(i, l.set(j, l.get(i)));
    }
    

    The JDK guys resort to a raw type, in order to handle this, locally. This is a strong statement indicating that this probably should be supported by the compiler, but for some reason (e.g. lack of time to formally specify this) just wasn't done

提交回复
热议问题