HI, why I can’t fill the arraylist in Java

This is my method:

public void Read() {
    try{
        File fXmlFile = new File("C://Students.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);

        doc.getDocumentElement().normalize();

        NodeList nList = doc.getElementsByTagName("student");

        Student s = new Student(); // Creating a new object

        for (int i = 0; i < nList.getLength(); i++) {
            Node nNode = nList.item(i);

            if (nNode.getNodeType() == Node.ELEMENT_NODE){
                Element eElement = (Element) nNode;

                s.First_Name = eElement.getElementsByTagName("firstname").item(0).getTextContent();
                Student.Last_Name = eElement.getElementsByTagName("lastname").item(0).getTextContent();

                Student.ID = eElement.getAttribute("id");
                Student.Spec = eElement.getElementsByTagName("spec").item(0).getTextContent();
                Student.Course = eElement.getElementsByTagName("course").item(0).getTextContent();

                Student.Ratingstr = eElement.getElementsByTagName("rating").item(0).getTextContent();

                students.add(new Student());
            }
        }
    }catch(Exception e){}
}

public static void main(String argv[]){
    Student y = new Student();
    y.Read();        
}

and these are my class fields:

ArrayList<Student> students = new ArrayList<>();
public static String First_Name;
public static String Last_Name;
public static String ID;
public static String Spec;
public static String Course;
public static String Ratingstr;
public float Rating;

Why I’m filling the second “s”-object or second student but not the first?
I mean when I wrote first index with my first object of Student in the first cycle then I need to fill second index with second Student but I fill First and the second index only with Second Student. I whrite over the first index in second loop. Why is that?


Source: java

Leave a Reply