Java_集合操作_使用细节

来源:互联网 发布:百度地图 数据开放 编辑:程序博客网 时间:2024/05/31 13:15

细节一:集合中存储的其实都是对象的引用而非对象本身

package test;import java.util.ArrayList;import java.util.List;public class test {public static void main(String args[]) {List<User> userList1 = new ArrayList<User>();List<User> userList2 = new ArrayList<User>();User user1 = new User();userList1.add(user1);userList2.add(user1);System.out.println("SET VALUE FOR USERLIST2:");for (User user : userList2) {user.setName("name");user.setPassword("password");}System.out.println("PRINT VALUE FOR USERLIST1:");for (User user : userList1) {System.out.println(user.getName());System.out.println(user.getPassword());}}public static class User {private String name;private String password;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}}}
输出:

SET VALUE FOR USERLIST2:
PRINT VALUE FOR USERLIST1:
name
password

设置userList2中元素的value,但是userList1中元素的value也发生了改变,证明集合中存放的是对象的引用。


细节二:集合中不能存储基本数值,但JDK1.5之后可以这样写,因为java会将基本数值自动装箱成为对象再将对象的引用存入集合中。

package test;import java.util.ArrayList;import java.util.Collection;public class test {public static void main(String args[]) {Collection coll = new ArrayList();coll.add(1);// 将编译后的class文件反编译可以看出等同于coll.add(Integer.valueOf(1));}}


0 0
原创粉丝点击