前几天写程序遇到了这样的一个问题:
Map<String, Object> args=getparameters(); Map<String, Object> hot_args=args; hot_args.put("sortItem","pv"); Map<String, Object> common_args=args; common_args.put("dateId","week");一直有问题,后来才发现,common_args的sortItem键值和hot_args的键值是一致的,并且在最后,args,hot_args,common_args都是一样的,考虑一番,才想起来这是由于深复制和浅复制的问题:
package text.copy; public class User implements Cloneable { private String name; private String passwd; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPasswd() { return passwd; } public void setPasswd(String passwd) { this.passwd = passwd; } public Object clone()//重写Cloneable接口的clone()方法 { User user=null; try{ user=(User)super.clone();//将一个实例克隆,并抛出异常 }catch(CloneNotSupportedException e) { e.printStackTrace(); } return user; } }使用:
User user1=new User(); user1.setName("Lily"); User user2=(User)user1.clone(); user2.setName("admin"); System.out.println("user1.name:"+user1.getName()); System.out.println("user2.name:"+user2.getName());结果:
user1.name:Lily user2.name:admin回到最上面,对于Map,我们不好去重写Map类或者HashMap类,但可以通过另外一种方式,HashMap的putAll()来实现:
Map<String, Object> args=getparameters(); Map<String, Object> hot_args=new HashMap<String, Object>(); hot_args.putAll(_args); hot_args.put("sortItem","pv"); Map<String, Object> common_args=new HashMap<String, Object>(); common_args.putAll(_args); common_args.put("dateId","week");这样,每次都重新创建一个HashMap对象,在改对象上添加键值,三者互不干扰。。。