一个类可以自己重新分配给另一个变量吗?

时间:2015-11-14 11:27:08

标签: java class object this

对于作业,我不得不在一个类中调整数组的大小,并且由于类的性质,更容易创建类的新对象然后重新分配自己?

让我尝试用代码解释

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'

那么,我们如何才能做到这一点?我是否只需要对其进行硬编码,或者是否有更好的方法来更改对象本身的引用?

任何建议都是适当的

2 个答案:

答案 0 :(得分:0)

继续这样:

<强> Foo.java

public class Foo{

    // String Array instance
    public String[] array; // I made this variable 'public' so that it would be accessible to the main method's class

    // Constructor with a String array as a variable to initialize it's instance
    public Foo(String[] array){
        this.array = array;
    }

    public void reassign(int length) {
        array = new String[length];
        array[0] = "Hello"; // String to display in the main() method
    }
}

<强> App.java

public class App {
    public static void main(String[] args) throws Exception{
        String[] tab = new String[1];
        tab[0] = "TempValue";
        Foo myArray = new Foo(tab);
        myArray.reassign(2); // new array with size = 2
        System.out.println(myArray.array[0]);
        myArray.array[1] = "World";
        System.out.println(myArray.array[1]);
    }
}

打印:

Hello
World

到控制台。这证明reassign方法有效。

答案 1 :(得分:0)

您可以通过重新分配内部数组来改变类:而不是String[] differentArray = {};执行array = {};。这将丢失先前存储的信息。

或者你可以返回一个新的foo对象:

public Foo reassign() {
  Foo temp = new Foo(...);
  return temp;
}

哪个合适取决于你想要达到的目标。