java 复制构造函数和防御性复制

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15020850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 18:14:36  来源:igfitidea点击:

Copy constructors and defensive copying

javadefensive-programming

提问by user2094103

What is a copy constructor?

什么是复制构造函数

Can someone share a small example that can be helpful to understand along with defensive copying principle?

有人可以分享一个有助于理解防御性复制原则的小例子吗?

回答by OldCurmudgeon

Here's a good example:

这是一个很好的例子:

class Point {
  final int x;
  final int y;

  Point(int x, int y) {
    this.x = x;
    this.y = y;
  }

  Point(Point p) {
    this(p.x, p.y);
  }

}

Note how the constructor Point(Point p)takes a Pointand makes a copy of it - that's a copy constructor.

请注意构造函数如何Point(Point p)获取 aPoint并制作它的副本 - 那是 a copy constructor

This is a defensivecopy because the original Pointis protected from change by taking a copy of it.

这是一个defensive副本,因为Point通过复制它可以保护原件免于更改。

So now:

所以现在:

// A simple point.
Point p1 = new Point(3,42);
// A new point at the same place as p1 but a completely different object.
Point p2 = new Point(p1);

Note that this is not necessarily the correctway of creating objects. It is, however, a goodway of creating objects that ensures that you never have two references to the same object by accident. Clearly this is only a good thing if that is what you want to achieve.

请注意,这不一定是创建对象的正确方法。但是,它是创建对象的方法,可确保您永远不会意外地对同一个对象进行两次引用。显然,如果这是您想要实现的目标,这只是一件好事。

回答by Joop Eggen

Copy constructors one often sees in C++ where they are needed for partly hidden, automatically invoked operations.

复制构造函数在 C++ 中经常看到,部分隐藏、自动调用的操作需要它们。

java java.awt.Pointand Rectanglecome to mind; also very old, mutable objects.

java java.awt.PointRectangle想到; 也是非常古老的可变对象。

By using immutable objects, like String, or BigDecimal, simply assigning the object reference will do. In fact, due to the early phase of Java after C++, there still is a silly copy constructor in String:

通过使用不可变对象,例如String, 或BigDecimal,只需分配对象引用即可。事实上,由于C++之后的Java早期阶段,String中仍然存在一个愚蠢的复制构造函数:

public class Recipe {
    List<Ingredient> ingredients;

    public Recipe() {
        ingredients = new ArrayList<Ingredient>();
    }

    /** Copy constructor */
    public Recipe(Recipe other) {
        // Not sharing: ingredients = other.ingredients;
        ingredients = new ArrayList<Ingredient>();
        ingredients.addAll(other.ingredients);
    }

    public List<Ingredient> getIngredients() {
        // Defensive copy, so others cannot change this instance.
        return new ArrayList<Ingredient>(ingredients);
        // Often could do:
        // return Collections.immutableList(ingredients);
    }
}

回答by Lakshmi

Copy constructor in java can be used when you need to clone an object

当你需要克隆一个对象时,可以使用java中的复制构造函数

class Copy {
   int a;
   int b;
  public Copy(Copy c1) {
    a=c1.a;
    b=c1.b;
  }
}

In java when you give Copy c2=c1; simply creates a reference to the original object and not the copy so you need to manually copy the object values.

在java中,当你给 Copy c2=c1; 只需创建对原始对象而不是副本的引用,因此您需要手动复制对象值。

See this:

看到这个:

回答by Alankar Srivastava

A copy constructor is used to create a new object using the values of an existing object.
One possible use case is to protect original object from being modified while the copied object can be used to work upon.

复制构造函数用于使用现有对象的值创建新对象。
一种可能的用例是保护原始对象不被修改,而复制的对象可用于处理。

public class Person  
{  
   private String name;  
   private int age;  
   private int height;  


/** 
 * Copy constructor which creates a Person object identical to p.  
 */  
   public person(Person p)  
   {  
      person = p.person;  
      age = p.age;  
      height = p.height;  
   }  
.
.
. 
}

Related to defensive copy hereis a good read

与防御性副本相关的这里是一个很好的阅读

回答by Mordechai

This is where you create a new object, by passing an old object, copying its values.

这是您通过传递旧对象并复制其值来创建新对象的地方。

Color copiedColor = new Color(oldColor);

instead of :

代替 :

Color copiedColor = new Color(oldColor.getRed(),
                              oldColor.getGreen(), oldColor.getBlue());