简体   繁体   English

Processing.org-按值传递对象

[英]Processing.org - Pass object by value

I am pretty new to this language. 我是这种语言的新手。 I have an object and I want to pass it by value to another method: 我有一个对象,我想按值将其传递给另一个方法:

// Drawings
class Drawings
{
   // Has some variables

   Drawings()
   {

   }

   // Hass some methods

} 

class History
{
    ArrayList<Drawings> prevDrawings;

    History()
    { 
        this.prevDrawings = new ArrayList<Drawings>();
    }

    void add(Drawings newDrawing) {}

}

Now, say I have a Drawings myDrawing and History myHistory , and I want to pass myDrawing by value to myHistory . 现在,说我有一个Drawings myDrawingHistory myHistory ,我想将myDrawing按值传递给myHistory The following way passes it by reference: 以下方式通过引用将其传递:

myHistory.add(myDrawing);

How can I then pass this by value? 我该如何通过价值传递呢?

Everything in Java, and therefore Processing, is already pass-by-value. Java中的所有内容(以及由此而来的Processing)都已经传递了值。 Nothing is passed by reference. 没有任何东西可以通过引用传递。

If that doesn't make sense, read this and then read this . 如果那没有意义,请阅读此内容 ,然后阅读此内容

What you might mean is that you want to pass a copy of the Object into a method. 您可能要表示的是要将对象的副本传递到方法中。 There are multiple ways to do that. 有多种方法可以做到这一点。 Let's say you have this as your Object: 假设您将其作为对象:

class MyObject{
   String thing1;
   double thing2;
   int thing3;
}

You could create a copy method outside of the MyObject class: 您可以在MyObject类之外创建一个复制方法:

public MyObject copy(MyObject original){
   MyObject copy = new MyObject();
   copy.thing1 = original.thing1;
   copy.thing2 = original.thing2;
   copy.thing3 = original.thing3;
}

You could create a copy method inside the MyObject class: 您可以在MyObject类中创建一个复制方法:

class MyObject{
   String thing1;
   double thing2;
   int thing3;

   public MyObject copy(){
      MyObject copy = new MyObject();
      copy.thing1 = this.thing1;
      copy.thing2 = this.thing2;
      copy.thing3 = this.thing3;
   }

}

Or you could create a copy constructor: 或者,您可以创建一个副本构造函数:

class MyObject{
   String thing1;
   double thing2;
   int thing3;

   public MyObject(MyObject copy){
      this.thing1 = copy.thing1;
      this.thing2 = copy.thing2;
      this.thing3 = copy.thing3;
   }
}

You could also use serialization, but that goes a little outside normal Processing. 您也可以使用序列化,但这超出了正常处理的范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM