The code below indicates that values are being returned by reference:
public class Playground {
public static void main(String[] args) {
Map<Integer, vinfo> map = new HashMap<Integer, vinfo>();
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;
}
}
Output:
1=false
2=false
3=false
In the code below, they are being returned by value. However; I am using the Integer object.
public class Playground {
public static void main(String[] args) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
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);
}
}
}
Output:
1=1
2=1
3=1
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().