我试图尽可能简化,不要用我的游戏中的代码墙向你发送垃圾邮件
假设我有一个类 XY 的Object,它包含Objects Z 的ArrayList。 如何从类 Z 中的方法中寻址 XY 对象的成员( int number )。
class XY {
static int nextID = 0;
final int id;
int number;
List<Z> zList = new ArrayList<Z>();
XY(int number) {
this.id = nextID++;
this.number = number;
zList.add(new Z(id));
}
...
class Z {
final int id;
Z (int id) {
this.id = id;
}
void getXYNumber() {
int n = // ?
}
}
我只能找到一种解决方法,因为在我的情况下,类 XY 也只是在类中存储为一个数组,现在调用它 ABC 和所有 Z 对象与 XY 类具有相同的 id ,其中包含 Z 对象,因此我可以使用此 id < / strong>从 Z 中的方法 getXYid 中识别 ABC 内的 XY 对象,我&#39; m呼叫。
class ABC {
static XY[] = new XY[]{12, 45, 86};
static XY getXY(int id) {
for(XY xy: xyList) {
if (xy.id = id) return xy;
}
}
}
class Z {
void getXYid() {
int n = ABC.getXY().number;
}
}
是否有任何关键字或某些内容可以获取特定的 XY ,它使用我正在调用的方法保存Z,或者这已经是最佳解决方案了?
注意:在这种情况下,标识类的成员是 int id ,它可以仅用作ABC类中 XY 数组的索引,但是在我的例子中,识别类的对象是一个名为所有者的枚举,对于 XY 对象中的所有 Z 对象都是相同的,所以那不会有用。
答案 0 :(得分:1)
在XY
中创建Z
类型的字段,并在创建Z
时设置其值。它也不需要复制id
字段。
class XY {
static int nextID = 0;
int id;
int number;
List<Z> zList = new ArrayList<Z>();
XY(int number) {
this.id = nextID++;
this.number = number;
zList.add(new Z(this));
}
class Z {
XY xy;
Z (XY xy) {
this.xy = xy;
}
int getXYId() {
return xy.id;
}
int getXYNumber() {
return xy.number;
}
}
这种循环引用通常被认为是不好的做法,在许多情况下表明您需要检查您的应用程序架构/设计。
答案 1 :(得分:1)
我相信有两个简单的解决方案。如果number
中XY
的值没有变化,我建议将number
传递给Z
的构造函数,如:
class Z {
int xyNumber
final int id;
Z (int id, int xyNumber) {
this.id = id;
this.xyNumber = xyNumber;
}
void getXYNumber() {
int i = // ?
}
}
在上面的示例中,您可以调用构造函数,如:new Z(id, number);
如果number的值发生变化,您可以将实际的XY
对象传递给Z
的构造函数。此对象是一个引用,因此如果原始更改,Z
对象内的版本也会更改。这会为您提供最新的number
值。将Z
对象传递给另一个XY
时,您可以使用currentXY
void setXY(XY)
class Z {
final int id;
XY currentXY;
Z (int id, XY currentXY) {
this.id = id;
this.currentXY = currentXY;
}
void getXYNumber() {
int i = // ?
}
void setXY(newXY) {
currentXY = newXY;
}
}
在上面的示例中,您可以调用构造函数,如:new Z(id, this);
。关键字this
会为您提供当前正在使用的对象,在您的情况下是XY
对象。