I wrote a little program that use ArrayList collection :
import java.util.Scanner;
import java.util.ArrayList;
class MyClass {
String name ;
String surname ;
int age ;
MyClass () {}
MyClass (String name,String surname,int age){
this.name = name;
this.surname= surname;
this.age=age;
}
void showAll () {
System.out.println("----------------------------------------------------------------------------------------");
System.out.println("Name: "+name+"\n"+"Surname: "+surname+"\n"+"Age: "+age);
}
}
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<MyClass> arrayData = new ArrayList<>();
MyClass obj= new MyClass();
int index ;
for (int i=1;i<=5;i++) {
System.out.println("-------------------------------------------------------------------------------------");
System.out.println("Data of person No "+i+" : ");
System.out.println("Name: ");
obj.name = input.nextLine();
System.out.println("Surname: ");
obj.surname = input.nextLine();
System.out.println("Age: ");
obj.age = input.nextInt();
input.nextLine();
arrayData.add(obj);
}
while(true) {
System.out.println("Put index: ");
index = input.nextInt();
input.nextLine();
arrayData.get(index).showAll();
}
}
}
But it doesn't work as expected because arrayData
store only the last received object obj
in all its elements.It seems there is a problem in the line :
arrayData.add(obj);
So i did some research on google and i found a way to fix the code by replacing the reference obj
with an instance of Myclas
like the flowing :
arrayData.add(new MyClass(obj.name, obj.surname, obj.age));
and it worked ! But i still can't understand why arrayData.add(obj);
doesn't work while it seems the same thing as arrayData.add(new MyClass(obj.name, obj.surname, obj.age));
?