Note that there are some explanatory texts on larger screens.

plurals
  1. POWhen Does HashMap.values()/HashMap.keySet() Return By Reference And When Does It Return By Value?
    primarykey
    data
    text
    <p>The code below indicates that values are being returned by reference:</p> <pre><code>public class Playground { public static void main(String[] args) { Map&lt;Integer, vinfo&gt; map = new HashMap&lt;Integer, vinfo&gt;(); map.put(1, new vinfo(true)); map.put(2, new vinfo(true)); map.put(3, new vinfo(true)); for(vinfo v : map.values()){ v.state = false; } printMap(map); } public static void printMap(Map m){ Iterator it = m.entrySet().iterator(); while(it.hasNext()){ Map.Entry pairs = (Map.Entry) it.next(); Integer n = (Integer) pairs.getKey(); vinfo v = (vinfo) pairs.getValue(); System.out.println(n + "=" + v.state); } } } class vinfo{ boolean state; public vinfo(boolean state){ this.state = state; } } </code></pre> <p>Output:<br> 1=false<br> 2=false<br> 3=false<br></p> <p>In the code below, they are being returned by value. However; I am using the Integer object.</p> <pre><code>public class Playground { public static void main(String[] args) { Map&lt;Integer, Integer&gt; map = new HashMap&lt;Integer, Integer&gt;(); map.put(1, 1); map.put(2, 1); map.put(3, 1); for(Integer n : map.values()){ n+=1; } printMap(map); } public static void printMap(Map m){ Iterator it = m.entrySet().iterator(); while(it.hasNext()){ Map.Entry pairs = (Map.Entry) it.next(); Integer n = (Integer) pairs.getKey(); Integer n2 = (Integer) pairs.getValue(); System.out.println(n + "=" + n2); } } } </code></pre> <p>Output:<br> 1=1<br> 2=1<br> 3=1<br></p> <p>How can I know when I am directly changing the value (or key for that matter) or I have to do a full .remove() and .put().</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload