结合在阵列中的Java引用 [英] Binding a Java reference in array
问题描述
我有这个非常简单的code。我试图找出我怎么能同时改变与对象引用数组首先被放入数组中的对象引用。 我想知道如何将两个引用/值绑定。
I have this very simple code. I am trying to figure out how I can simultaneously alter the object reference in the array with the object reference that was first placed into the array. I want to know how to bind the two references/values.
在JavaScript中,这是非常类似于Java中的按值传递方面,我们大概可以做的最好的就是用Object.observe()像这样:的 http://www.html5rocks.com/en/tutorials/es7/observe/
In JavaScript, which is very similar to Java in terms of passing by value, the best we probably can do is to use Object.observe() like so: http://www.html5rocks.com/en/tutorials/es7/observe/
但与Java,我不知道是否有做到这一点,而无需编写自己的库的好办法?
but with Java, I wonder if there is a good way to do this without writing your own library?
public class ArrayRefVal {
public static void main(String[] args) {
ArrayList<Object> al = new ArrayList<Object>();
Object s = new Object();
al.add(s);
s = null;
System.out.println(al.get(0));
}
}
同样的:
public class ArrayRefVal {
public static void main(String[] args) {
ArrayList<Object> al = new ArrayList<Object>();
Object s = new Object();
al.add(s);
al.set(0, null);
System.out.println(s);
}
}
原来JavaScript有这一个相同的行为如Java。我怎么能以某种元素绑定对象在数组中,这样当我更改的元素数组中它改变了原来的对象?
turns out JavaScript has the same behavior as Java on this one. How can I somehow bind the element in the array with the object s, such that when I change the element in the array it changes the original object?
我提到过这个了吗? 我想知道如何将两个引用/值绑定。
Did I mention this already? I want to know how to bind the two references/values.
推荐答案
您不能做到这一点在你喜欢的方式,因为你不能改变在Java中现有的字符串,无论是你可以更新本地变量取值
非明确的方式(不使用赋值运算符如 =
或 + =
)。如果你想这样的间接,可以引入一些中间的参考对象:
You cannot do it in the way you like, because you cannot change the existing String in Java, neither can you update local variable s
in non-explicit way (without using assignment operator like =
or +=
). If you want such indirection, you can introduce some intermediate reference object:
public class ArrayRefVal {
static class Ref<T> {
T obj;
public Ref(T obj) {
this.obj = obj;
}
@Override
public String toString() {
return String.valueOf(obj);
}
}
public static void main(String[] args) {
ArrayList<Ref<String>> al = new ArrayList<>();
Ref<String> s = new Ref<>("hiii");
al.add(s);
al.get(0).obj = "barg";
System.out.println(s); //prints "barg"
}
}
不过你应该关心在每一个地方,有必要使用参考
。
这篇关于结合在阵列中的Java引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!