Java由一个对象List筛选或者浅复制得到的另一个对象List里面的引用和原List里的引用指向同一个地址,修改其中一个List里的共有对象时,同时会影响到两个List里存放的对象
package test;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class CodeTest {
private String value;
public CodeTest(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public static void main(String[] args) {
/*String fileName ="aaaa.dio.doc";
String substring = fileName.substring(fileName.lastIndexOf("."));
System.out.println(fileName);
System.out.println(substring);*/
/*String s = " ";
System.out.println(s.trim().isEmpty());*/
List<CodeTest> list1 = new ArrayList<>();
list1.add(new CodeTest("a"));
list1.add(new CodeTest("b"));
list1.add(new CodeTest("c"));
list1.add(new CodeTest("d"));
List<CodeTest> list2 = list1.stream().filter(s -> s.value.equals("a") || s.value.equals("b")).collect(Collectors.toList());
System.out.println(list1);
System.out.println(list2);
System.out.println("=================================");
for (CodeTest codeTest : list1) {
System.out.println(codeTest.value);
}
System.out.println("=================================");
for (CodeTest codeTest : list2) {
System.out.println(codeTest.value);
}
System.out.println("=================================");
// list2.set(0,"1");
// list2.set(1,"2");
//修改list2里面对象的属性值,list1里的对象的属性值也会改变
for (CodeTest codeTest : list2) {
codeTest.setValue("change");
}
for (CodeTest codeTest : list1) {
System.out.println(codeTest.value);
}
System.out.println("=================================");
for (CodeTest codeTest : list2) {
System.out.println(codeTest.value);
}
System.out.println("=================================");
System.out.println(list1);
System.out.println(list2);
}
}
运行结果: