因為懶加載機(jī)制弯屈,在轉(zhuǎn)換過的集合上,如果在function里生成了一個新對象恋拷,再執(zhí)行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]}]