2013-02-25 93 views
-3

我在將我的類「行」中的元素添加到我的類「表」中時遇到了一些問題。類表擴展了ArrayList,因此arrayList的每個元素都應該包含一個類Row。 如果我創建一個類表,並手動運行addApplicant(Row app)方法,我可以添加一個行。不過,我希望一行創建時自動將它自己添加到類表。 這裏是我到目前爲止的代碼: 表類:在另一個類的ArrayList中添加一個類

public class Table extends ArrayList<Row>{ 

public String appArray[]; 

/** 
* Constructor for objects of class Table 
*/ 
public Table() 
{ 
} 

public void addApplicant(Row app) 
{ 
    add(app); 
} 

public void listArray() //Lists the Array[] 
{ 
    for(int i = 0; i<appArray.length; i++) 
    { 
     System.out.println(appArray[i]); 
    } 
}} 

Row類:

public class Row{ 

private String appNumber; 
private String name; 
private String date; 
private String fileLoc; 
private String country; 
public ArrayList<String> applicant; 

public Row(String appNumber, String name, String date, String fileLoc, String country) 
{ 
    this.appNumber = appNumber; 
    this.name = name; 
    this.date = date; 
    this.fileLoc = fileLoc; 
    this.country = country; 
    applicant = new ArrayList<String>(); 
    applicant.add(appNumber); 
    applicant.add(name); 
    applicant.add(date); 
    applicant.add(fileLoc); 
    applicant.add(country); 
} 

private void convertToString() 
{ 
    for(int i = 0; i<applicant.size(); i++) 
     { 
      String appStr = applicant.toString(); 
     } 
}} 

很想念我的任何想法?謝謝你的幫助。

+0

將Table實例作爲參數添加到行構造函數。比從該行的構造函數調用到:table.AddApplicantRow(this) – 2013-02-25 14:31:52

+0

這是不好的方式來擴展ArrayList在你的情況 – bsiamionau 2013-02-25 14:33:11

回答

2

你沒有引用表類。你可以做的,就是表對象傳遞到構造函數的要求,所以你的構造看起來就像這樣:

public Row(String appNumber, String name, String date, String fileLoc, String country, Table table) 

,並呼籲

table.addApplicant(this); 

當您完成信息加載到行對象。這會將此行對象的引用添加到您的表中:)

+0

Thankyou這麼多!這正是我需要的。我完美的作品:) – Hoggie1790 2013-02-25 14:37:12

+0

請記住標記它作爲未來讀者的答案:)並在另一個說明中,使用繼承這種事情是不正確的方式來解決它。因爲你只需要ArrayList類的一小部分功能,所以你應該使用[Composition](http://en.wikipedia.org/wiki/Class_diagram#Composition) – christopher 2013-02-25 14:38:23

+0

我會在10分鐘的塊已經過去了。我會研究構圖。再次感謝你的幫助。 – Hoggie1790 2013-02-25 14:41:37

相關問題