当第一次传递数组到构造函数时更新

时间:2015-11-04 15:13:58

标签: java

当构造函数参数是列表并且列表通过外部函数更新时,进程如何?有"传递参考"参数是数组或列表时的系统。但是如何更新对象?是否使用了任何复制构造函数或如何使用?

假设我们有两个用户定义的类Point和Curve。我们用Point对象填充了列表。然后我们使用List of Points构造我们的Curve对象。

List<Point> points=new ArrayList<>();
points.add(Point(0,1));
points.add(Point(0,0));
Curve c=new Curve(points);

然后我们将Point对象添加到Points of Points。

points.add(Point(1,1));

Curve对象如何受到影响?

2 个答案:

答案 0 :(得分:0)

c本质上是指向points对象的指针。这意味着c的“值”内部包含类中某处“points”对象的地址。

从现在开始,您在points对象中所做的更改将反映到c对象。

答案 1 :(得分:0)

java中只有pass-reference-by-value但没有纯pass-by-reference。如果Curve将原始值存储到引用points并且points未重新初始化,那么您仍在使用相同的引用,因此List位于c }也会改变(它仍然是相同的参考)。

以下是一个小例子,可以在您处理相同的参考时显示,何时不显示。

public class Curve{

    private List<Point> points = new ArrayList<>(0);

    public Curve(List<Point> points) {
        this.points = points;
    }

    public Curve(List<Point> points, boolean flag) {
        this.points.addAll(points);
    }

    void print() {
        for(Point p : points) {
            System.out.println(p);
        }
    }

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

        @Override
        public String toString() {
            return "X = " + x +"\nY = " + y ;
        }

    }

    public static void main(String[] args) {
        List<Curve.Point> points = new ArrayList<Curve.Point>(0);
        points.add(new Curve.Point(0,0));
        points.add(new Curve.Point(0,1));
        // Care for compiler error just one should be used
        Curve c = new Curve(points,true); // Using this constructor copies the elements and the folloing add wont affect c
        Curve c = new Curve(points); // Using this constructor uses the same list so the following add will affect c
        points.add(new Curve.Point(1,1));
        c.print();
    }
}
相关问题