0

我在将“行”类中的字符串添加到“表”类时遇到了一些麻烦。因此,每次我创建一个名为 row 的类时,它都会将提交的字符串添加到“Table”类的同一个实例中。这是我的行类:

public class Row extends ArrayList<Table>{
public ArrayList<String> applicant;
public String row;
/**
 * Constructor for objects of class Row
 */
public Row()
{
    applicant = new ArrayList<String>();
    convertToString();
    applicants(row) //<------ This is the arrayList in the Table class that i wish to           add the row to
}

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

这是我的“行”课:

public class Table {

    public ArrayList<String> applicants;

    public String appArray[];

    /**
     * Constructor for objects of class Table
     */
    public Table() {
        applicants = new ArrayList<String>();
    }

    public void addApplicant(String app) {
        applicants.add(app);
        toArray();
    }

    public void toArray() {
        int x = applicants.size();
        appArray = applicants.toArray(new String[x]);
    }

    public void list() // Lists the arrayList
    {
        for(int i = 0; i < applicants.size(); i++) {
            System.out.println(applicants.get(i));
        }
    }

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

任何帮助将非常感激。

4

1 回答 1

2

申请人(行)不是行/表类中的方法。

如果您希望将行添加到 Row 类中的 Arraylist,请使用 add 方法

申请人.add(row) 方法。

您还应该注意,Table 和 Row 关系不需要您创建扩展 Table 类的 Row 类。它应该是两个独立的类。因此 Table 和 Row 类将具有一对多的关系。因此修改 Table 类,使其能够添加 Row 类的多个实例。

我不知道您要做什么,但可以说您的 Row 类应该包含两件事,即 rowID 和申请人名称。还有一个表类,它有很多行代表每个申请人。

所以 Row 类看起来像这样:

public class Row extends ArrayList<Table>{
String applicantName;
int applicantID;


/**
 * Constructor for objects of class Row
 */
public Row(int appID, String appName)
{
applicantName = appName;
applicantID = appID;

}

public getApplicantName(){
return applicantName;
}

public getApplicantID(){
return applicantID; 
}


}

表类将如下所示:

public class Table {

    public ArrayList<Row> applicants;

    public String appArray[];

    /**
     * Constructor for objects of class Table
     */
    public Table() {
    applicants = new ArrayList<String>();
    }

    public void addApplicant(Row app) {
    applicants.add(app);

    }


    public void list() // Lists the arrayList
    {
    for(int i = 0; i < applicants.size(); i++) {
        Row row = (Row) applicants.get(i);  
        System.out.println("Applicant ID: "+ row.getApplicantID() +
        "  Applicant Name: " + row.getApplicantName());
    }
    }

}

所以以下列方式使用上述类:

Row r1 = new Row(1, "Tom");
Row r2 = new Row(2, "Hoggie");
Row r3 = new Row(3, "Julie");

表表 = 新表();

table.addApplicant(r1);
table.addApplicant(r2);
table.addApplicant(r3);

//所以现在当你调用下面的方法列表时,它会打印所有的申请者//他们的ID

table.list();
于 2013-02-21T22:14:39.403 回答