java - Java 在转换为 Object 后更改变量的值
问题描述
我试图在将变量转换为对象后更改它。这在 Java 中是否可行,或者是否有其他选项可以做类似的事情?
Double a = 1.;
Object o = a;
Double b = (Double)o;
b = 2.;
System.out.println(a); // print 2
解决方案
如果有两个引用指向同一个对象,则不能更改两个引用中的一个,如果它们分配给一个新对象。
Double a = 1.,
Double b = a;
Double b = 2.; // here b now points to new object. a is not changed. Now you have two separate variables pointing to separate objects.
如果你真的需要,那么你需要使用具有 setter/better 的包装类来操纵内部状态
DoubleWrapper a = new DoubleWrapper(2); // not a standard JDK class. You will need to write it yourself
DoubleWrapper b = a;
b.set(1);
System.out.println(b.get()); // prints 1
System.out.println(a.get()); // also prints 1
推荐阅读
- c++ - 在获得证书之前调用 OCSP 装订 cb
- php - 在 laravel 中对数据数组进行分页并在 vuejs 中使用无限滚动的最佳方法
- python - 删除数组的特定值:Python
- angularjs - 如何在angularjs中结合字母数字和特殊类来验证我的密码?
- c++ - static_cast 与不相关的类
- python - 代码未上传,但在控制台中打印
- powershell - Splunk 为 powershell 节输入配置 cron 计划
- c# - WPF - 锁定网格(容器)星形大小
- jmeter - 获取 onRun 单元格文本并用作过滤器中的参数
- java - 如何根据从第一个选择标签中选择的值填充第二个 struts2 选择标签?