【发布时间】:2015-11-14 11:27:07
【问题描述】:
对于分配,我必须在类中调整数组的大小,并且由于类的性质,创建类的新对象然后重新分配本身更容易?
让我试着用代码解释一下
public class foo {
// String Array instance
private String[] array;
// Constructor with a String array as a variable to initialize it's instance
public foo(String[] array){
this.array = array;
}
public void reassign() {
String[] differentArray = {};
foo temp = new foo(differentArray);
// Now here is where my problem lies
this = temp;
// out of this I get the following error
// The left-hand side of an assignment must be a variable
}
}
// Let also just say that for the sake of argument, I can't reassign
// 'array' to 'differentArray'
那么,我们将如何进行这项工作?我只需要围绕它进行硬编码还是有更好的方法来更改对对象本身的引用?
任何建议都会被采纳
【问题讨论】:
-
您无法更改
array引用而不为其分配新引用。您只能混淆重新分配。 -
看来我得到的答案只是让我做一些硬编码,结果证明这就是我所做的。不过,我遇到的主要问题是,我能否将“foo”(我所在的类本身)重新分配给不同的“foo”(在该类中创建的对象)。我认为答案是否定的,因为方法不是静态的(我认为)。不过,感谢您的所有意见,这真的很有帮助。