【问题标题】:Java Copy Constructor with the "this" keyword [duplicate]带有“this”关键字的Java复制构造函数[重复]
【发布时间】:2017-12-15 23:54:15
【问题描述】:

我有一个关于 java 的非常普遍的问题。 我想知道是否有一种简单的方法可以在 java 中重新创建这个 c++ 代码:

class A 
{

public:
  int first;
  int second;

  A(const A& other) {
    *this = other;
  }

...
}

所以基本上是一个复制构造函数,您可以在构造函数中将 A 的现有对象传递给 a 的新对象,它将复制内容并构建 A 的现有对象的精确副本。

尝试

class A {
  int first;
  int second;

  public A(A other){        
    this = other;
  }
 ...
}

很遗憾不起作用,因为 eclipse 告诉我“this”不允许出现在赋值的左侧,因为它不是变量。

我知道我会得到相同的结果:

class A {
      int first;
      int second;

      public A(A other){        
        this.first = other.first;
        this.second = other.second;

      }
     ...
    }

但我想知道是否有更简单的方法,因为有时你有更多的类变量。

提前致谢!

【问题讨论】:

  • 你可以创建一个私有构造函数来接收你的所有变量,并让所有其他构造函数以某种方式调用它。
  • 你的意思是一个构造函数,它接受该对象的一个​​实例,然后复制它的数据。这可能就这么简单。
  • @Daedric 完全正确 - 但不必单独复制其变量。 (我想知道我在提交问题后是否误用了复制构造函数这个词 - 这是否导致混淆?)

标签: java c++ constructor copy this


【解决方案1】:

Java 语言没有定义更简单的方法,但是有一些技巧可以让您这样做:

  1. 通过序列化克隆对象:http://www.avajava.com/tutorials/lessons/how-do-i-perform-a-deep-clone-using-serializable.html:前提条件 - 结构中类的所有属性必须是原始的或标记为 Serializable 的类
  2. toString() -> fromString(String s) - 必须实现相应的方法
  3. POJO 和 bean 可以通过 Jackson 等可用库使用中间 XML/JSON 表示轻松重构。

据我所知,直接映射后最有效的方法是通过序列化机制。

【讨论】:

  • 好的,非常感谢,我去看看序列化!
  • 是的,序列化很好,但与简单的构造函数相比,它会涉及更多。
【解决方案2】:

您在该类的第三个版本中拥有的是合法的 java,它与您的 C++ 类做同样的事情,但是我认为没有比您编写的更简单的方法了。

【讨论】:

    【解决方案3】:

    回收代码的最佳方式:

    class A {
    
       int first;
       int second;
    
       public A(int f, int s){        
          this.first = f;
          this.second = s;
       }
    
       public A(A a){
          this(a.first, a.second); // id use getters instead ofc.
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-15
      • 1970-01-01
      • 1970-01-01
      • 2019-09-05
      • 2013-12-17
      • 1970-01-01
      • 1970-01-01
      • 2019-03-02
      相关资源
      最近更新 更多