Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with using double as value in hashmap

Tags:

java

I have a double as the value in hashmap with the key as a String. If I update the variable that was added as a value to the hashmap independently, instead of updating it in the hashmap, the updated value does not get reflected. That is when I use the key to get the value I get the value as 0.0 instead of the updated value. I am not able to understand why this happens. Please throw some light on this. Also, is there some other way of updating the value in hashmap by updating the variable. A sample code of what I am talking about is below:

import java.util.HashMap;
public class TestDouble{
    public Double d1 = 0.0;
    public Double d2 = 0.0;
    public Double d3 = 0.0;
    private HashMap<String,Double> hm;

    public TestDouble(){
        hm = new HashMap<String,Double>();
        hm.put("D1",d1);
        hm.put("D2",d2);
        hm.put("D3",d3);
    }

    public void updateD1(double d){
        d1 = d;
    }

    public void updateD2(double d){
        d2 = d;
    }

    public void updateD3(double d){
        d3 = d;
    }

   public Double getValue(String key){
        Double val = (Double)hm.get(key);
        return val;
    }

    public static void main(String args[]){
        TestDouble td =new TestDouble();
        td.updateD1(10.10);
        td.updateD2(20.20);
        td.updateD3(30.30);
        System.out.println("Value of D1 from HashMap = "+td.getValue("D1")+" from actual variable = "+td.d1);
        System.out.println("Value of D2 from HashMap = "+td.getValue("D2")+" from actual variable = "+td.d2);
        System.out.println("Value of D3 from HashMap = "+td.getValue("D3")+" from actual variable = "+td.d3);
    }
}

The output I get is:

Value of D1 from HashMap = 0.0 from actual variable = 10.1
Value of D2 from HashMap = 0.0 from actual variable = 20.2
Value of D3 from HashMap = 0.0 from actual variable = 30.3
like image 479
Shamsuddin Khakiyani Avatar asked Dec 17 '22 07:12

Shamsuddin Khakiyani


1 Answers

Double is immutable. You can not update its value. Instead you can reference to another instance of a Double

d1 has a reference to a 0d:

Double d1 = 0d;

If we do another initialization it will be referencing another value:

d1 = 1d;

On the other hand HashMap is mutable, i.e. its internal state can be changed:

Map<String, Double> map = new HashMap<String, Double>();
map.put("first", 0d);
map.put("first", 1d);
System.out.println("first = " + map.get("first"));

The output will be:

first = 1.00

Bear in mind that we have replaced the value associated with the key first, it is not updated.

like image 166
Boris Pavlović Avatar answered Dec 18 '22 19:12

Boris Pavlović