2

*免責事項: 私は Java の初心者なので、ご容赦ください。

hw_list次のように、ファイルから読み取られた文字列を含むという配列リストがあります。

    [Doe John 1 10 1 Introduction.java, Doe Jane 1 11 1 Introduction.java, Smith Sam 2 15 2 Introduction.java Test.java]

配列の各要素を独自のサブリストにすることができたので、次のように出力されます。

    [Doe John 1 10 1 Introduction.java] 
    [Doe Jane 1 11 1 Introduction.java]
    [Smith Sam 2 15 2 Introduction.java Test.java]

しかし、上記のように各要素を独自のサブリストに分割するには、次のように各サブリストを手動で書き出す必要があります。

    List<String> student1 = hw_list.subList(0, 1);
    List<String> student2 = hw_list.subList(1, 2);
    List<String> student3 = hw_list.subList(2, 3);

私の問題は、読み込まれる文字列の数が変わる可能性があるため、事前に作成するサブリストの数がわからないことです。

ループを使用して新しいリストを動的に作成し、各要素をに基づいて分割する方法はありますhw_list.size()か?

このようなものは可能ですか:

    for(int i=0; i<hw_list.size(); i++){
        List<String> student(i) = hw_list.sublist(i, i+1)
    }

TL;DR

配列のすべての要素に対して新しいリストを作成するループを取得するにはどうすればよいですか?

4

2 に答える 2

1

dasblinkenlight のアドバイスに従ったら、各文字列を学生に変換します。

List<Student> students = new ArrayList<Student>();
for(String studentRep:hw_list){
    students.add(Student.studentFromString(studentRep));
}

次に、生徒のリストを次のように処理できます。

for(Student student:students){
    System.out.println(student.getFirstName());
}
于 2013-10-13T15:38:33.823 に答える
1

コーディングしたものは正常に実行されますが、論理的には意味がありません。要素を追加して拡張できない単一項目のサブリストは、基になる配列リストでも変更されます。

代わりに、次のように、名前、姓、セクション、提出日など、関連する意味のあるアイテムのグループとして単一の要素に格納されたデータを表すクラスを作成する必要があります。

public class Student {
    private String firstName;
    private String lastName;
    private List<String> fileNames;
    private int section;
    private int date; // Consider changing this to a different type
    public Student(String firstName, String lastName, int section, int date) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.section = section;
        this.date = date;
        fileNames = new ArrayList<String>();
    }
    public String getFirstName() { return firstName; }
    public String getLastName() { return lastName; }
    public int getSection() { return section; }
    public int getDateSubmitted() { return date; }
    public List<String> getFileNames() { return fileNames; }
}

String次に、次のように、を受け取り、を生成するメソッドを作成できますStudent

private static Student studentFromString(String studentRep) {
    String[] tokens = studentRep.split(" ");
    Student res = new Student(tokens[0], tokens[1], Integer.parseInt(tokens[2]), Integer.parseInt(tokens[3]));
    // You can ignore tokens[4] because you know how many files are submitted
    // by counting the remaining tokens.
    for (int i = 5 ; i != tokens.length ; i++) {
        res.getFileNames().add(tokens[i]);
    }
    return res;
}
于 2013-10-13T15:32:00.193 に答える