2015-11-04 67 views
-1

當構造函數參數是列表並且列表通過外部函數更新時,過程如何?當參數是一個數組或列表時,有「傳遞引用」系統。但是如何更新對象?是否使用過任何拷貝構造函數?當第一次傳遞數組到構造函數更新時

我們假設我們有兩個用戶定義的類Point和Curve。我們用Point對象填充我們的列表。然後我們用點列表構造我們的曲線對象。

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

然後我們在Point列表中添加一個Point對象。

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

曲線對象如何受到影響?

+0

*'points.Add' typo'points.add' – rajuGT

+0

曲線對象現在在列表中有3個點。 java中的所有東西都是通過值傳遞的,曲線對象的引用與'points'不同,但是指向同一個List(哈哈)。 – user3719857

+0

@ user3719857如果沒有看到'Curve'的代碼,我們不能完全知道這是真的。如果構造函數正在製作列表的深層副本,那麼添加到'points'不會影響它。 – Tgsmith61591

回答

0

在java中,只有pass-reference-by-value但沒有純粹的pass-by-reference。如果Curve將原始值存儲爲points的參考值,並且points未重新初始化,那麼您仍在處理相同的參考,因此Listc也會更改(它仍然是相同的參考)。

下面是一個小例子,當你在使用相同的參考和不使用時應該顯示你。

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(); 
    } 
} 
+0

謝謝!這對我來說更加清楚:) – BeginnerGuy

+0

Kevin,值得注意的是,你的'布爾標誌'實際上並沒有完成除了表示一個新的構造方法簽名以外的其他任何事情。如果你真的想,你可以將'true'的值複製到'false'的列表和值中,而只是在內部賦值。 – Tgsmith61591

0

c本質上是一個指向點對象的指針。這意味着c的「值」在內部包含類中某個地方的「點」對象的地址。

從這裏開始,您在點對象中所做的更改將反映到c對象。

+0

這是*錯*! 'c'不是*指向'points'的指針,它是它自己的對象! 'points'只是作爲參數傳遞給'Curve',我們不能斷言'points'的引用仍然保留在'Curve'裏面而沒有看到'Curve'類的源代碼(或者查看'在'add'操作之後,c'受到影響)。如果構造函數正在製作列表的深層副本,則添加到點不會影響它。 – Tgsmith61591

相關問題