1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Apex 開発:deepCloneとCloneの区別

Last updated at Posted at 2020-05-19

普通の方(clone)

``` Account a = new Account(Name='Acme', BillingCity='New York');

Account b = new Account();
Account[] q1 = new Account[]{a,b};

Account[] q2 = q1.clone();
q1[0].BillingCity = 'San Francisco';

System.debug(q1[0].BillingCity); // San Francisco
System.debug(q2[0].BillingCity); // San Francisco

同じポインターのため、q1修正すると、q2の値も変更されるとのことです。

<h2>deepCloneの方</h2>

Account a = new Account(Name='Acme', BillingCity='New York');

Account b = new Account();
Account[] q1 = new Account[]{a,b};

Account[] q2 = q1.deepClone();
q1[0].BillingCity = 'San Francisco';

System.debug(q1[0].BillingCity); // San Francisco
System.debug(q2[0].BillingCity); // New York


List accts = [SELECT CreatedById, CreatedDate, LastModifiedById,
LastModifiedDate, BillingCity
FROM Account
WHERE Name='Acme' OR Name='Salesforce'];

// Clone list while preserving timestamp and user ID fields.
Account[] q3 = accts.clone();

// Verify timestamp fields are preserved for the first list element.

System.debug(q3[0].Id);
System.debug(q3[0].CreatedById);
System.debug(q3[0].CreatedDate);
System.debug(q3[0].LastModifiedById);
System.debug(q3[0].LastModifiedDate);

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/550974/95b6f8fa-6f4a-4d38-f64b-c4f73c841697.png)

List accts = [SELECT CreatedById, CreatedDate, LastModifiedById,
LastModifiedDate, BillingCity
FROM Account
WHERE Name='Acme' OR Name='Salesforce'];

// Clone list while preserving timestamp and user ID fields.
Account[] q3 = accts.deepClone(false,false,false);

// Verify timestamp fields are preserved for the first list element.

System.debug(q3[0].Id);
System.debug(q3[0].CreatedById);
System.debug(q3[0].CreatedDate);
System.debug(q3[0].LastModifiedById);
System.debug(q3[0].LastModifiedDate);

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/550974/e1babc7e-1406-cfbc-a364-4e4d5027b946.png)

「Id」、参照のみ「タイムスタンプ」と「自動採番」はこまめに扱いできる。
 ディフォルト:false
1
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?