Java中的copyOf Arrays方法是否执行深层复制?

时间:2017-05-19 18:53:23

标签: java arrays

我想知道Arrays类中的copyOf方法是否创建了新对象,然后将其传递给复制的数组,或者仅创建引用现有对象的新变量。我试图构建一些测试它的代码:

import java.awt.Point;
import java.util.Arrays;

public class PointTest2 {

  public static void main(String[] args) {
  Point[] array1 = new Point[2];
  Point[] array2 = new Point[2];

  for(int i = 0; i < array1.length; i++) {
    array1[i] = new Point(i, i);
  }

  array2 = Arrays.copyOf(array1, 2);
  array1[0] = array1[1];

  array1[1] = array2[0];

  System.out.println(Arrays.toString(array1));
  System.out.println(Arrays.toString(array2));
  System.out.println(array1[0] == array2[1]);
  }
}

该程序返回:

[java.awt.Point[x=1,y=1], java.awt.Point[x=0,y=0]]

[java.awt.Point[x=0,y=0], java.awt.Point[x=1,y=1]]

true

似乎如果copyOf仅传递了引用,那么结果数组应该具有两个元素作为对具有x = 1y = 1的点对象的引用。但是,我认为如果复制的数组被赋予了对象的新副本,那么equals运算符应该返回false,因为引用应该是不同的。有人可以帮我理解这里发生了什么吗?提前致谢!

1 个答案:

答案 0 :(得分:0)

Arrays.copyOf(T [] original,int newLength)方法创建一个具有新长度的新数组。但是将值复制到新数组。因此它是浅拷贝。如果您正在存储对象类型,那么它们将是相同的。

源代码

        // Branch the pipeline here for requests that start with "/signalr"
        app.Map("/signalr", map =>
        {
            // Setup the CORS middleware to run before SignalR.
            // By default this will allow all origins. You can 
            // configure the set of origins and/or http verbs by
            // providing a cors options with a different policy.
            map.UseCors(CorsOptions.AllowAll);
            var hubConfiguration = new HubConfiguration 
            {
                // You can enable JSONP by uncommenting line below.
                // JSONP requests are insecure but some older browsers (and some
                // versions of IE) require JSONP to work cross domain
                // EnableJSONP = true
            };
            // Run the SignalR pipeline. We're not using MapSignalR
            // since this branch already runs under the "/signalr"
            // path.
            map.RunSignalR(hubConfiguration);
        });