![](/img/trans.png)
[英]How to store different objects of arrayList in memory and later retrieve them?
[英]How do I loop through an arrayList to store them as different objects?
我有一個字符串數組列表。
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個參數,每四個參數將存儲一個新的學生對象。 因此,所有這些對象都將傳遞到“學生和項目”列表中。
這些對象的代碼如下所示。
在項目類中:
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類。 最好的方法是什么?
謝謝。
我將假定您要存儲項目和大量對象以供以后使用。 您可以采用以下方法:
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]));
}
}
注意:在創建Person
和Student
的對象時,我已經任意傳遞了參數,並假定string
s的順序將保持一致。 希望您可以根據構造函數參數序列傳遞參數。
首先,您的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.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.