如何遍历arrayList以将它们存储为不同的对象?

时间:2017-11-22 06:18:43

标签: java arrays object arraylist data-structures

我有一个字符串的Arraylist。

private List<String> listGroup = new ArrayList<String>();

listGroup的一个元素是 "CyberHacking Tools,CLS,Tim Hemmingway,2,P132303,Tyler Johnson,APP,M,P132304,Patty Henderson,APP,F"

我需要将前五个元素存储到项目对象中,该项目对象在项目类中具有构造函数,同时循环其余元素以将它们存储到Student对象中,并在Student类中使用构造函数。学生对象只保存4个参数,每四个参数后,它将存储一个新的学生对象。因此,所有这些对象都将被传递到学生和项目列表中。

这些对象的代码如下所示。

在Project类中:

    public Project(int noOfProj, String title, String sch, String superv, int NoOfStudent) {
        this.noOfProj = noOfProj;
        this.title = title;
        this.school = sch;
        this.supervisorName = superv;
        this.noOfStudent = NoOfStudent;
        // this.projIndex = projCode;
    }

这是Project对象:

Project p = new Project(title, school, supervisorName, noOfStudents);

我分别有一个项目类,学生类,FileReader类和JFrame类。最好的方法是什么?

谢谢。

2 个答案:

答案 0 :(得分:0)

我假设你想存储项目和stundent对象供以后使用。以下是您可以采取的方法:

        List<Project> personList = new ArrayList<Project>(); //store list of projects
                    List<Student> listStudent = new ArrayList<Student>(); //store list of students

               for (String str : listGroup) {

                    String arr[] = str.split(",");
                    //as student object takes 4 arguements and "noOfStudents" is the number of "Student" objects found in the string
                    int noOfStudents = (arr.length / 4)-1;
                    Project p = new Project(Integer.parseInt(arr[3]),arr[0],arr[1],arr[2],noOfStudents);
                    personList.add(p);
                    for(int i=4;i<arr.length-4;i+=4)
                    {
                        listStudent.add(new Student(arr[i],arr[i+1],arr[i+2],arr[i+3]));
                    }
                }

注意: 创建PersonStudent的对象时我假设{{1}的序列任意传递了参数} s将是一致的。希望您可以根据构造函数参数序列传递参数。

答案 1 :(得分:0)

首先,您的Project构造函数似乎有4个参数,而不是5。说,

    // considering this as your sample line -
    // String line = "CyberHacking Tools,CLS,Tim Hemmingway,2,P132303,Tyler Johnson,APP,M,P132304,Patty Henderson,APP,F"

    String[] tuple = line.split(",");

    // Get first 4 tuples for Project. 
    // CyberHacking Tools,CLS,Tim Hemmingway,2
    Project project = new Project(tuple[0], tuple[1], tuple[2], tuple[3]);

    // Iterate over rest of the tuples for Student. 
    // P132303,Tyler Johnson,APP,M 
    // P132304,Patty Henderson,APP,F
    for (int i = 4; i < tuple.length; i += 4) {
        Student student = new Student(tuple[i], tuple[i + 1], tuple[i + 2], tuple[i + 3]);
        // add the student object to List<Student> here. 
    }