java中按值传递对象
所以假设我已经将
ArrayList<E> X = new ArrayList<E>();
X 传递给了某个参数:
Something Y = new Something(X);
它将通过引用而不是通过值传递 X,而我不想要这个....class Something 有一个 Arraylist 类型的字段,该字段应该与其自身不同,并且我不想遍历该死的数组列表并单独设置它只是为了实例化该字段...
有没有一种方法可以轻松地使 Java 按值而不是引用传递任何对象参数,而不必在其上实现可克隆接口我所有的东西都是令人痛苦的
so suppose i have
ArrayList<E> X = new ArrayList<E>();
and I pass X into some parameter:
Something Y = new Something(X);
it will pass X by reference rather than by value and I don't want this....class Something has a field with Arraylist type that is supposed to be distinct to itself and I don't want to go and iterate through the damn arraylist and set it individually just to instantiate the field...
is there a way to easily make Java pass any object parameters by value rather than reference without having have to implement cloneable interface on all my objects which is a pain in the butt
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于 Java 不允许直接操作指针,因此无法取消引用指针。你必须忍受参考。如果你想防止传递的对象被修改,你必须克隆它或使其不可变(如
String
)。另请记住,对象引用是按值传递的。因此,如果我们采用 C++ 意义上的“按引用传递”,那么“Java 具有按引用传递”之类的语句并不准确。As Java do not allow direct pointer manipulation, you cannot dereference a pointer. You have to live with references. If you want to prevent the passed object from being modified, you have to clone it or make it immutable (like
String
). Also keep in mind that object references are passed-by-value. So statements like "Java has pass-by-reference" is not exact, if we take pass-by-reference in the C++ sense.它实际上按值传递 X。 (Something 构造函数无法更改调用代码中的变量 X。)X 恰好是对 ArrayList 的引用,而不是 ArrayList。你可以尝试:
It actually passes X by value. (The Something constructor can't change the variable X in the calling code.) X happens to be a reference to an ArrayList, not an ArrayList. You could try:
您可以传递一个不可修改的列表,而不是每次都创建一个新对象。该列表是只读的,如果用户想要进行任何修改,则必须创建另一个列表。
ArrayList 的构造函数采用现有列表,读取其元素(不修改它们!),并将它们添加到新列表中。
Instead of creating a new object everytime you can pass an unmodifiable list. This list is read-only and the user has to create another list if he wants to make any modification.
The constructor of ArrayList takes an existing list, reads its elements (without modifying them!), and adds them to the new List.