Java 中的参考 [英] References in Java

查看:43
本文介绍了Java 中的参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关如何在 java 中只能按值传递以及交换两个对象的内容的唯一方法是将 then 放入数组中...按值传递对数组对象的引用,然后使用对交换 0-1 数组位置的引用.

i was reading about how you can only pass by value in java and that the only way to swap the contents of two objects is by putting then in an array...passing the reference to the array object by value and then using that reference to swap 0-1 array location.

但我还有一个问题:假设我创建了一个数组,例如:

But i have a further question on this: Suppose i create an array such as:

List<Integer> array = new ArrayList<Integer>();
Integer a = new Integer(1);
array.add(a);

所以我的问题是当我将一个对象添加"到一个数组中时(在这种情况下是 Integer 对象)……我是只是将对象的引用存储在数组中,还是实际上将对象的内容复制数组...

So my question is when i "add" an object to an array (in this case Integer object)...do I just store the reference to the object in the array or do I actually copy the content of the object in the array...

假设,假设我们在 java 中有一个删除引用"语句,..那么这会保留数组中对象的值吗?

Hypothetically, let's say we have a "delete reference" statement in java,..so will this retain the value of the object in the array?

List<Integer> array = new ArrayList<Integer>();
Integer a = new Integer(1);
array.add(a);
delete a;

那么数组仍然会保存正确的值吗??

So will the array still hold the correct value??

推荐答案

假设,假设我们在 java 中有一个删除引用"语句,..那么这会保留数组中对象的值吗?

Hypothetically, let's say we have a "delete reference" statement in java,..so will this retain the value of the object in the array?

由于我们不知道这个假设陈述在做什么,所以很难说.

Since we do not know what this hypothetical statement is doing, that is hard to tell.

您的 ArrayList 保存的是对 Integer 对象的引用.您对该对象的任何其他引用都指向完全相同的实例.

What your ArrayList holds is a reference to an Integer object. Any other reference you have to that object points to the exact same instance.

对于 Integer,这没有什么区别,因为 Integer 是不可变的.

With Integer, that does not make much of a difference, because Integer is immutable.

尝试使用像 StringBuilder 这样的可变对象来查看效果:

Try with a mutable object like StringBuilder to see the effect:

List<Object> array = new ArrayList<Object>();
StringBuilder a = new StringBuilder("xxxxxx");
array.add(a);

a.setLength(0);  // clear the contents

System.out.println(array.get(0));  // will not print "xxxxxx" anymore

这篇关于Java 中的参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆