定义了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

解决方案 »

  1.   

    Integer(1)是不可修改的?
    Integer temp = test.get("abc");
    temp+=2;这些都是新生成了一个,不是修改以前的。
      

  2.   

    调试和判断显示貌似put进去的value是一个copy
    即使对保留引用进行操作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"));
      

  3.   

    string 类和 包装类都是不可变的。 即使你把引用传出来又如何?!
      

  4.   

    >发现test.getKey("xxx")返回的不是对Integer的引用
    你错了,它返回的的确是引用问题出在temp += 2;
    这里是用Integer同一个int进行计算,从jdk1.5开始,java会自动为我们完成拆箱与装箱,
    它会先将Integer拆成int,然后与int=2进行计算,得到3,然后再将int=3包装成Integer,
    Integer.valueOf(3),这里就生成了一个新对象了
      

  5.   

    我上面最后一句不太严谨
    Integer.valueOf(3)不是生成一个新对象,这个对象它已经被高速缓存了,
    这里只是将它从池中拿出来而已,所以与你从map中得到的引用不是一个
      

  6.   

    应该是值赋予和引用的问题。
    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
      

  7.   

       HashMap<String,Integer> test;
       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
      

  8.   

    像這種情況其實可以建個類的   
    建個類 tempInteger   里面的屬性是Integer  在實現方法add()對屬性的操作
    這不就OK了
      

  9.   

    我又回来了。  Integer temp = test.get("abc");// 对象test.get("abc")
       temp+=2;// 要仔细观察这一句 
    //其实这一句, 新增加了一个对象.新对象 = test.get("abc") + 2希望大家能明白。
    System.out.println(test.get("abc"));//仍旧是1,不是3
    //test.get("abc")仍是前面的那个对象
      

  10.   

    哦,原来Integer是immutable的,不过Integer的API文档说明上也不提一句。
      

  11.   

    我记得有的,是Java的优化机制。对于
    Primary 类型的简单封装类,都是这样处理的!
      

  12.   

    > 哦,原来Integer是immutable的,不过Integer的API文档说明上也不提一句。不用说呀,你在 Integer 对象身上找不到任何一个 method 能够改变对象的值,这就已经说明问题了  :-)
      

  13.   

    的确 看Integer所实现的hashCode方法返回的是什么
    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的包装类