guava transform小坑

因为懒加载机制,在转换过的集合上,如果在function里生成了一个新对象,再执行set操作,实际上是没用的。因为下次访问还是会重新生成"新"对象,就忽略了修改操作。

  @Test
    public void testlist(){
        List<Node> nodes= Lists.newArrayList();
        Node node=new Node();
        node.setList(Lists.newArrayList(new Long(111)));
        nodes.add(node);

        List<Node> list=Lists.transform(nodes, new Function<Node, Node>() {
            @Nullable
            @Override
            public Node apply(@Nullable Node input) {
                Node node=new Node();
                node.setList(Lists.newArrayList(new Long(123)));
                return node;
            }
        });

        for(Node n:list){
            System.out.println(n);
        }

        System.out.println(list);

        for(Node n:list){
            n.setList(Lists.newArrayList(new Long(222)));
        }
        System.out.println(list);

    }
    class Node{
        List<Long> list;

        public List<Long> getList() {
            return list;
        }

        public void setList(List<Long> list) {
            this.list = list;
        }

        @Override
        public String toString() {
            return "Node{" +
                    "list=" + list +
                    '}';
        }
    }

如果不生成新对象,则修改可以生效,因为是同一个实例并且值被改变了。

 @Test
    public void testlist(){
        List<Node> nodes= Lists.newArrayList();
        Node node=new Node();
        node.setList(Lists.newArrayList(new Long(111)));
        nodes.add(node);

        List<Node> list=Lists.transform(nodes, new Function<Node, Node>() {
            @Nullable
            @Override
            public Node apply(@Nullable Node input) {
                return input;
            }
        });

        for(Node n:list){
            System.out.println(n);
        }

        System.out.println(list);

        for(Node n:list){
            n.setList(Lists.newArrayList(new Long(222)));
        }
        System.out.println(list);

    }
Node{list=[111]}
[Node{list=[111]}]
[Node{list=[222]}]

但同样,不新建对象,也有可能存在function中方法因为懒加载,覆盖其它set方法情况

  @Test
    public void testlist(){
        List<Node> nodes= Lists.newArrayList();
        Node node=new Node();
        node.setList(Lists.newArrayList(new Long(111)));
        nodes.add(node);

        List<Node> list=Lists.transform(nodes, new Function<Node, Node>() {
            @Nullable
            @Override
            public Node apply(@Nullable Node input) {
//                Node node=new Node();

                input.setList(Lists.newArrayList(new Long(123)));
                return input;
            }
        });

        for(Node n:list){
            System.out.println(n);
        }

        System.out.println(list);

        for(Node n:list){
            n.setList(Lists.newArrayList(new Long(222)));
        }
        System.out.println(list);

    }
Node{list=[123]}
[Node{list=[123]}]
[Node{list=[123]}]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容