-1

I'm trying to wrap my head around why the value associated with a hashMap isnt updated when the reference is updated. Since Java is pass-by-value-by-reference shouldn't the value associated with BIN1 simply point to the new object that now 'curr points to?

class Solution {
    static class Card{
        private final String bin;
        private final String cardType;
        private final String cardName;
        private int trustScore;

        public Card(String bin, String cardType, String cardName, int trustScore){
            this.bin = bin;
            this.cardType = cardType;
            this.cardName = cardName;
            this.trustScore = trustScore;
        }

        public String toString(){
            return this.bin + " " + this.cardName + " "+ this.cardType + " " + this.trustScore;
        }
    }
    static class CardProcessor{
        private Map<String, Card> map;

        CardProcessor(){
            this.map = new HashMap<>();
        }
        public void store(String bin, String cardType, String cardName, int trustScore){
            if(!map.containsKey(bin))
                map.put(bin, new Card(bin, cardType, cardName, trustScore));
            else {
                Card curr = map.get(bin);
                if(curr.trustScore < trustScore) {
                    curr = new Card(bin, cardType, cardName, trustScore);
                    map.put(bin, curr); // Why is this line necessary to point BIN1 to the new value of card? Since Curr is a reference to Card shouldn't curr simply point to the new value supplied?
                }
            }
        }
    }
    public static void main(String[] args) {
        CardProcessor cp = new CardProcessor();
        cp.store("BIN1", "VISA", "BoA", 1);
        cp.store("BIN1", "VIEX", "BACU", 5);
        System.out.println(cp.map.entrySet());
    }
}
MuleNoob
  • 127
  • 1
  • 6
  • 1
    I think you're confusing pass-by-value-of-reference with pass-by-reference. `Card curr` is an entirely new variable that points to the same thing as `map.get(bin)`, and then you make `curr` point to a new, different `Card` object. – Louis Wasserman May 06 '22 at 01:59
  • "Java is pass-by-value-by-reference": no it isn't. – user207421 May 06 '22 at 02:23
  • 2
    Java is not "pass values by reference". It is "pass references by value". In Java **everything** is passed by value. No exceptions. So ... of course you are confused by the behavior. You have the wrong model. (And "pass by reference by value" is meaningless word-soup.) – Stephen C May 06 '22 at 02:29

1 Answers1

0

First you pointed curr to the result of map.get(bin):

Card curr = map.get(bin); 

After that you pointed curr to a new object:

curr = new Card(bin, cardType, cardName, trustScore);

The object whose reference was returned by map.get(bin) did not change

map.get(bin).cardType = "VIEX"

would have changed the content within that object.

user207421
  • 305,947
  • 44
  • 307
  • 483