import java.util.HashMap;
import java.util.Map;
public class Main {
public static String KEY="TEST-KEY";
public static void main(String[] args) {
Map<String,Filed> map= new HashMap<>();
map.put(KEY,new Filed(100));
Filed v = map.get(KEY);
v.setCount(200);
System.out.println(map.get(KEY).getCount());
}
}
class Filed{
private int count;
public Filed(int count) {
this.count = count;
}
public void setCount(int count) {
this.count = count;
}
public int getCount() {
return count;
}
}
输出结果为: 200
Golang版本
package main
import "fmt"
const KEY = "TEST-KEY"
type Filed struct {
Count int
}
func main() {
fileds := make(map[string]Filed)
fileds[KEY] = Filed{Count: 100}
filed := fileds[KEY]
filed.Count = 200
fmt.Println(fileds[KEY].Count)
}
输出结果为: 100
原因是这里从map中拿到的对象是局部变量,对局部变量的修改不影响map中对应key的值
与java相同功能的代码
package main
import "fmt"
const KEY = "TEST-KEY"
type Filed struct {
Count int
}
func main() {
fileds := make(map[string]*Filed)
fileds[KEY] = &Filed{Count: 100}
filed := fileds[KEY]
filed.Count = 200
fmt.Println(fileds[KEY].Count)
}
输出结果为: 200
这里从map中拿到的对象是一个指针,对指针的修改影响map中对应key的值