一个有意思的Java集合类
程序员文章站
2022-03-12 16:33:26
...
package com.shanxian.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String userId;
private String userName;
private String age;
}
测试类:
package com.shanxian.test;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import com.shanxian.entity.User;
public class Test001 {
public static void main(String[] args) {
User u1= new User("1","孙悟空","23");
User u2= new User("2","猪八戒","24");
User u3= new User("3","沙僧","25");
User u4= new User();
System.out.println("修改前===u1:"+u1);
u4 = u1;
u4.setUserName("小白龙");
System.out.println("修改后===u1:"+u1);
List list = new LinkedList<User>();
list.add(u1);
list.add(u2);
list.add(u3);
System.out.println("list1=="+list);
for (int i = 0; i < list.size(); i++) {
User u5= new User();
u5 = (User) list.get(i);
if(u5.getUserId().equalsIgnoreCase("1")) {
u5.setUserName("如来");
}
}
System.out.println("list2=="+list);
}
}
运行结果:
修改前===u1:User(userId=1, userName=孙悟空, age=23)
修改后===u1:User(userId=1, userName=小白龙, age=23)
list1==[User(userId=1, userName=小白龙, age=23), User(userId=2, userName=猪八戒, age=24), User(userId=3, userName=沙僧, age=25)]
list2==[User(userId=1, userName=如来, age=23), User(userId=2, userName=猪八戒, age=24), User(userId=3, userName=沙僧, age=25)]
我印象中 修改前 修改后 u1 的userName会改变。但是没想到list集合中也能改,尝试一下果然也会。
Java中引用果然是有意思
上一篇: F - Feel Good Gym - 101334F 经典思维(前缀和)
下一篇: 尺取法