-1

異なるクラスのオブジェクトを含むarraylistの理解に問題があります。私は6つのオブジェクトを持っています。すべてのオブジェクトには共通の2つの属性があります。(ID、Type)すべてのオブジェクトには独自の属性があります。2 atr(ID、Type)でmainObjectクラスを作成しました。他のオブジェクトはmainObjectを拡張して、

class mainClass{
    this.id=id;
    this.type=type;
}
class extendedClass extends mainClass{
    super(ID,Type);
    this.atr1=atr1;
}

class extendedClass2 extends mainClass{
    super(ID,type);
    this.atr2=atr2;
    this.atr3=atr3;
}

ファイルから情報を読みました。

FileInputStream fstream = new FileInputStream("data.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
    // Print the content on the console
    String s[] = strLine.split("\\|");
    mainClass myObj = new mainClass(s[0], s[1]);

ArrayList<mainClass> items = new ArrayList<mainClass>();
items.add(myObj);

すべてのオブジェクトをファイルから1行ずつ読み取り、配列リストに格納する必要があります。これはどのようにすればよいですか?試しましたArrayList<Object> list = new ArrayList<Object>が、機能しません。ポイントはファイルからすべてのオブジェクトを読み取り、選択された属性(id、type)に従ってそれらをソートします。

4

1 に答える 1

3

次のリストが必要であることは正しいですmainClass

ArrayList<mainClass> items = new ArrayList<mainClass>();

ただし、この行は while ループ内ではなく前に配置する必要があります。

ArrayList<mainClass> items = new ArrayList<mainClass>();

while ((strLine = br.readLine()) != null) {
    // etc...
    items.add(myObj);
}
于 2012-11-26T12:33:37.190 に答える