2014-10-16 110 views
0

我已經創建了一個Rectangle類,在for循環中我每次都通過循環創建一個新的Rectangle對象。如果我的理解是正確的,那麼每次創建一個新的Rectangle時,先前創建的Rectangle對象都不可訪問(代碼當前寫入的方式),因爲引用變量矩形現在指向最近創建的Rectangle對象。每次通過循環創建新對象時,允許我們訪問每個對象的最佳方式是什麼?我知道一種方法是創建一個List並將每個新創建的Rectangle添加到列表中。在循環中創建對象

public class RectangleTest { 

    public static void main(String[] args) { 

     for (int i=1;i<5;i++){ 
      Rectangle rectangle = new Rectangle(2,2,i); 
      System.out.println(rectangle.height); 
     } 
    } 
} 


public class Rectangle { 

    int length; 
    int width; 
    int height; 

    public Rectangle(int length,int width,int height){ 
     this.length = length; 
     this.width = width; 
     this.height = height; 
    } 

} 
+2

使用的'陣列/ List''Rectangles' – TheLostMind 2014-10-16 12:28:17

+1

什麼是你想通過保存參考文獻的實現?列表將是一個選項,但如果您提供上下文,則可能是其他選項。 – 2014-10-16 12:32:19

+0

我認爲這是不好的安置,如果你需要的東西不是本地的實際迭代循環,定義它在它之外。 – 2014-10-16 13:27:14

回答

2

您需要將創建的引用存儲在某個列表或數組中。

List<Rectangle> list = new ArrayList<>(); 

for (int i=1;i<5;i++){ 
     Rectangle rectangle = new Rectangle(2,2,i); 

     list.add(rectangle); 

     System.out.println(rectangle.height); 
    } 


System.out.println(list.get(0).height); 
0

您應該創建一個ArraList或一個LinkedList:

public class RectangleTest { 
    public static void main(String[] args) { 
     List<Rectangle> listOfRectangles = new LinkedList<Rectangle>(); 
     for (int i=1;i<5;i++){ 
     Rectangle rectangle = new Rectangle(2,2,i); 
     listOfRectangles.add(rectangle); 
     System.out.println(rectangle.height); 
     } 
    } 
} 


public class Rectangle { 

    int length; 
    int width; 
    int height; 

    public Rectangle(int length,int width,int height){ 
     this.length = length; 
     this.width = width; 
     this.height = height; 
    } 

}