Does Java return by reference or by value

前端 未结 4 1635
旧时难觅i
旧时难觅i 2020-12-14 09:38

I have a HashMap:

private HashMap cardNumberAndCode_ = new HashMap();

And later I do this:

相关标签:
4条回答
  • 2020-12-14 09:47

    The get method returns a copy of the reference to the stored integer...

    Assigning a new value to the variable storing this copy in order to point to the value 10 will not change the reference in the map.

    It would work if you could do balance.setValue(10), but since Integer is an immutable class, this is not an option.

    If you want the changes to take affect in the map, you'll have to wrap the balance in a (mutable) class:

    class Balance {
        int balance;
        ...
    }
    
    Balance balance = cardNumberBalance_.get(cardNumber);
    System.out.println(balance.getBalance());
    balance.setBalance(10);
    Balance newBalance = cardNumberBalance_.get(cardNumber);
    System.out.println(newBalance.getBalance());
    

    But you would probably want to do something like this instead:

    cardNumberBalance_.put(cardNumber, 10);
    
    0 讨论(0)
  • 2020-12-14 10:01

    The result of assignment

    balance = 10;
    

    is that a new instance of Integer is created with value of 10, and its reference is assigned to balance variable. It does not change the object that you get from the map, that is the object stored in the map is unchanged.

    If you need to change the value of balance, you have to wrap it in a mutable class just like aioobe describes.

    0 讨论(0)
  • 2020-12-14 10:04

    The Integer variable contains a reference to an Object. The Integer object is immutable and you cannot change it. When you perform

    balance = 10; // replace the previous Integer reference with a different one.
    

    The normal way to do this is to use

    cardNumberBalance_.put(cardNumber, 10);
    

    An alternative which is not used so often is to use AtomicInteger or use your own MutableInteger

    private final Map<String, AtomicInteger> cardNumberAndCode_ = new HashMap<String, AtomicInteger>();
    
    AtomicInteger balance = cardNumberBalance_.get(cardNumber);
    balance.set(10);
    
    0 讨论(0)
  • 2020-12-14 10:06

    Java does not support pass-by-reference (and return-by-reference). See Is Java "pass-by-reference" or "pass-by-value"?

    0 讨论(0)
提交回复
热议问题