对象引用数组 [英] Array of object references

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

问题描述

在 Java 中,让自定义对象 o 的类型为 CustomObject.然后CustomObject o2 = o; 将在不将o 的内容复制到o2 的情况下进行引用.但是对于 CustomObjects:

In Java, let a custom object o is of type CustomObject. Then CustomObject o2 = o; would make a reference without copying the contents of o to o2. But will this behaviour remain for an array of CustomObjects:

CustomObject[] os = new CustomObject[2];
os[1] = o;
os[2] = o;

os[1]os[2] 是引用还是 o 的直接副本,从而分离对象?

Will os[1] and os[2] be references or they will be direct copies of o and thus separate objects?

推荐答案

嗯,你实际上是指 os[0]os[1] 因为数组是 0-基于Java...但是是的,它们将是参考.两个数组元素将引用同一个对象.

Well, you actually mean os[0] and os[1] as arrays are 0-based in Java... but yes, they'll be references. Both array elements will refer to the same object.

重要的是,o 也不是一个对象:

Importantly, o isn't an object either:

  • o 是一个变量:它有一个名字和一个值
  • o 的值是一个引用:要么为空,要么引用一个对象
  • 对象具有字段,属于特定的执行时间类型等
  • o is a variable: it has a name and a value
  • The value of o is a reference: it's either null, or it refers to an object
  • An object has fields, is of a certain execution-time type, etc

表达式的值(无论是简单的变量值、方法调用的结果还是其他任何东西)从不在 Java 中是 object - 它是 总是一个引用或一个原始值.

The value of an expression (whether it's a simple variable value, the result of a method call or whatever) is never an object in Java - it's always either a reference or a primitive value.

Java 语言规范定义数组的方式一组变量:

The way the Java Language Specification defines arrays is just as a collection of variables:

一个数组对象包含许多变量.变量的数量可能为零,在这种情况下,数组被称为空.数组中包含的变量没有名称;相反,它们由使用非负整数索引值的数组访问表达式引用.这些变量称为数组的组件.如果一个数组有 n 个分量,我们说 n 是数组的长度;使用从 0 到 n - 1 的整数索引引用数组的组件.

An array object contains a number of variables. The number of variables may be zero, in which case the array is said to be empty. The variables contained in an array have no names; instead they are referenced by array access expressions that use non-negative integer index values. These variables are called the components of the array. If an array has n components, we say n is the length of the array; the components of the array are referenced using integer indices from 0 to n - 1, inclusive.

所以这真的有点像做:

// Creating the pseudo-array
CustomObject o0 = null;
CustomObject o1 = null;

// Populating it
o0 = o;
o1 = o;

与以往一样,赋值运算符只是将右侧的值复制到左侧.该值是一个参考.

As ever, the assignment operator just copies the value of the right hand side to the left hand side. That value is a reference.

这篇关于对象引用数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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