Sunday, July 10, 2022

[FIXED] Why isn't this HashMap value being updated via reference?

Issue

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());
    }
}

Solution

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.



Answered By - Lynn Tan
Answer Checked By - Gilberto Lyons (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.