I am making a simple array of objects in Java, a portion of my code is the following
public class Student{
private String name;
private double score;
public Student(String name){
this.name=name;
this.score=score
}
public class Classroom{
private Student[] listStu;
private int sc;
public addStu(Student stu){
listStu[sc]=stu;
sc++;
}
public Student[] getClassroom(){
return listStu;
}
public int getNum(){
return sc;
}
public printList(){
for (int i=0;i<sc;i++){
System.out.pritnln(listStu[i].getName());
}
}
and in the main class I program this:
Classroom c=new Classroom();
Student[] stuList;
int nStu;
Student s1=new Student("michael",3.0);
Student s2=new Student("larry",4.0);
c.addStu(s1);
c.addStu(s2);
stuList=c.getClassroom();
nStu=c.getNum();
the problem is when I modify an object of my class stuList in the main class, something like:
stuList[0].setName("peter");
I see when I call my printList method, that the data inside my array has also been modified (in my case the name of "michael" is changed by "peter"). The question that I have is how to make a copy of my array of objects into the stuList of the main class so that this array does not interfere with my original data? Is this procedure really necessary or is it unlikely this situation to happens?
Thanks