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