我有一个名为"info“的字符串的ArrayList,每个字符串都包含有关我的类学生会实例的信息。我尝试将Arraylist转换为数组,然后使用split方法解析它。
String[] Stringinfo = new String[info.size()];
Stringinfo = info.toArray(Stringinfo);
解析完每一行后,我尝试在for循环中创建一个新对象,并将其添加到学生ArrayList中。每当我创建这个新对象--学生,以前添加到学生ArrayList中的其他对象--都被更改为这个新对象。
String[] temp;
for(int i = 1; i < LineCount + 1 ; i++)
{
temp = Stringinfo[i].split(" ");
Student s = new Student(Integer.parseInt(temp[0]), Integer.parseInt(temp[1]), Integer.parseInt(temp[2]), Integer.parseInt(temp[3]), Integer.parseInt(temp[4]));
Students.add(s);
}
我试着在不同的地方打印学生,在创建新对象之前,一切都是正常的。在任何时候,所有对象都具有与最后创建的对象相同的属性值。
这是学生类构造函数:
public Student(int certif, int class_id, int ave, int i, int a)
{
certification_num = certif;
class_id = class;
average_point = ave;
student_id = i;
age = a;
}
我搜了很多遍,却找不到答案。很抱歉,如果答案很明显,我是刚接触Java的。任何帮助都将不胜感激。提前谢谢。
编辑:
public class Student{
public Student(){}
public Student(int certif, int class, int ave, int i, int a)
{
certification_num = certif;
class_id = class;
average_point = ave;
student_id = i;
age = a;
}
public static int get_certification_num(){
return certification_num;
}
public static int get_class_id(){
return class_id;
}
public static int get_average_point(){
return average_point;
}
public static int get_id(){
return student_id;
}
public static int get_age(){
return age;
}
private static int certification_num;
private static int class_id;
private static int age;
private static int node_id;
private static int student_id;
}
发布于 2015-10-01 09:26:10
首先,我建议你改变你的学生班级如下:
public class Student
{
private int certification_num;
private int class_id;
private int average_point;
private int student_id;
private int age;
public int getCertification_num() {
return this.certification_num;
}
// Do this for all variables
public void setCertification_num(int certif) {
this.certification_num = certif;
}
// Do this for all variables
}
在那之后,你可以轻松地使用你的学生班级。在其他情况下,当你没有或不需要所有信息的时候。
填充您的数组:
ArrayList<Student> students = new ArrayList<Student>();
for(int i = 1; i < LineCount + 1 ; i++)
{
String[] temp;
temp = Stringinfo[i].split(" ");
Student s = new Student();
s.setCertification_num(Integer.parseInt(temp[0]);
//Do for all other fields
Students.add(s);
}
https://stackoverflow.com/questions/32883653
复制相似问题