Home  >  Q&A  >  body text

java - For the swap function in the Collections class, why does the source code need to define a new final List variable l to point to the incoming list?

JDK1.7 source code is as follows:

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

What is the meaning of this sentencefinal List l = list? Wouldn't it be the same if you directly manipulate the passed in list?

I am a newbie in self-learning Java. I am a little confused when I see this. I hope the seniors can help me clear up my doubts. Thank you very much!

淡淡烟草味淡淡烟草味2712 days ago753

reply all(1)I'll reply

  • 漂亮男人

    漂亮男人2017-05-17 10:07:33

    Try it:

    import java.util.List;
    
    public class Test {
        public static void swap(List<?> list, int i, int j) {
            list.set(i, list.set(j, list.get(i)));
        }
    }

    Compilation error:

    .\Test.java:7: 错误: 无法将接口 List<E>中的方法 set应用到给定类型;
            list.set(i, list.set(j, list.get(i)));
                            ^
      需要: int,CAP#1
      找到: int,CAP#2
      原因: 参数不匹配; Object无法转换为CAP#1
      其中, E是类型变量:
        E扩展已在接口 List中声明的Object
      其中, CAP#1,CAP#2是新类型变量:
        CAP#1从?的捕获扩展Object
        CAP#2从?的捕获扩展Object
    1 个错误

    Becauselist的类型是List<?>, we don’t know the specific type, so we can only take out an Object from the list, but cannot insert it into the list.

    So convert it to List.

    or replace it with List<T>:

    public static <T> void swap(List<T> list, int i, int j) {...}

    reply
    0
  • Cancelreply