*免责声明:我是一个 Java super 菜鸟,所以请耐心等待。
我有一个名为 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;博士
如何获得一个循环来为数组的每个元素创建一个新列表?
最佳答案
您编写的代码运行良好,但逻辑上没有意义:您所拥有的单项子列表无法通过添加更多元素来扩展,并且它们也会随着底层数组列表的变化而改变。
您应该做的是构建一个类,将存储在单个元素中的数据表示为一组相关的、有意义的项目,例如名字、姓氏、部分和提交日期,如下所示:
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;
}
关于java - 如何动态分割数组列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19346717/