定义了HashMap<String,Integer> test,发现test.getKey("xxx")返回的不是对Integer的引用,因为更改该返回的Integer将不会影响到HashMap里的值。
然而自定义了一个Test的类,即HashMap<String,Test>返回的却是引用,修改返回值可以影响HashMap里的Test的值。前一种情况导致每次更新Integer的值需要不停的插入HashMap,除了自己定义一个Integer类,其他请问有什么更好的解决方法没?
比如: HashMap<String,Integer> test;
test.put("abc",new Integer(1));
Integer temp = test.get("abc");
temp+=2;
System.out.println(test.get("abc"));//仍旧是1,不是3
然而自定义了一个Test的类,即HashMap<String,Test>返回的却是引用,修改返回值可以影响HashMap里的Test的值。前一种情况导致每次更新Integer的值需要不停的插入HashMap,除了自己定义一个Integer类,其他请问有什么更好的解决方法没?
比如: HashMap<String,Integer> test;
test.put("abc",new Integer(1));
Integer temp = test.get("abc");
temp+=2;
System.out.println(test.get("abc"));//仍旧是1,不是3
解决方案 »
- 问下关于继承的问题
- java手动生成mysql 备份文件
- 寻求答案:如何用JAVA程序发送邮件附件(非JAVAMAIL类),主要是发送附件格式
- 高手来,"String s[]=new String[0];"有意义吗?再看......
- 请问怎样取得网站网页上的一个数据?
- 谁帮我看看这小段程序最后结果是什么?在线等,谢谢啦
- 哪里有JDBC for MySQL驱动程序:mm.mysql??
- 关于一个entity bean的一点困惑,解决后立即给分(100分)
- applet 中的classpath问题
- 书上的一个关于数据封装的例题,为何运行出错?请高手指点。
- 请问java竖向进度条怎么实现?在线等
- JAVA企业开发
Integer temp = test.get("abc");
temp+=2;这些都是新生成了一个,不是修改以前的。
即使对保留引用进行操作HashMap<String, Integer> test = new HashMap<String, Integer>();
Integer temp = new Integer(1);
test.put("abc", temp);
temp += 2;
System.out.println(test.get("abc"));
你错了,它返回的的确是引用问题出在temp += 2;
这里是用Integer同一个int进行计算,从jdk1.5开始,java会自动为我们完成拆箱与装箱,
它会先将Integer拆成int,然后与int=2进行计算,得到3,然后再将int=3包装成Integer,
Integer.valueOf(3),这里就生成了一个新对象了
Integer.valueOf(3)不是生成一个新对象,这个对象它已经被高速缓存了,
这里只是将它从池中拿出来而已,所以与你从map中得到的引用不是一个
temp是Integer类型,是值,而不是引用。
这么说吧:
Map test=new HashMap();
test.put("abc",new ArrayList());
List temp =(List) test.get("abc"); //这个temp是一个引用
temp.add("1");
temp.add("2");
System.out.println(((List)test.get("abc")).size());//打印结果是2
test.put("abc",new Integer(1));
Integer temp = test.get("abc");//其中temp是一个新的引用变量//同时integer class 是一个不变的
temp+=2;
//其中temp是一个新的引用变量
System.out.println(test.get("abc"));//仍旧是1,不是3
建個類 tempInteger 里面的屬性是Integer 在實現方法add()對屬性的操作
這不就OK了
temp+=2;// 要仔细观察这一句
//其实这一句, 新增加了一个对象.新对象 = test.get("abc") + 2希望大家能明白。
System.out.println(test.get("abc"));//仍旧是1,不是3
//test.get("abc")仍是前面的那个对象
Primary 类型的简单封装类,都是这样处理的!
a hash code value for this object, equal to the primitive int value represented by this Integer object.
从这个意义上讲 只要Integer对象的intValue改变了 它所返回的hash code值也就改变了 它也就成了另外一个对象了
所以引用还是引用 只是immutable 这一点和String很像 虽然String不是primitive type的包装类