【问题标题】:Can a class reassign itself to another variable within itself?一个类可以将自己重新分配给自身内部的另一个变量吗?
【发布时间】: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”(在该类中创建的对象)。我认为答案是否定的,因为方法不是静态的(我认为)。不过,感谢您的所有意见,这真的很有帮助。

标签: java class object this


【解决方案1】:

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

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

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

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

【讨论】:

  • 第二个选项听起来更符合我的目标,只是我希望类本身成为我在其中创建的新“Foo”对象。
  • 您介意解释一下吗?我很困惑为什么不是这样。
【解决方案2】:

继续往下:

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 方法有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-31
    • 1970-01-01
    • 1970-01-01
    • 2019-08-22
    • 1970-01-01
    • 2021-10-24
    • 2023-02-16
    • 1970-01-01
    相关资源
    最近更新 更多