-1

I have created a class named Test with (name and surname variables) plus getter and setter, then I made a List with Test type. I use set method to set variables value and then I try to add klass.setName(nminput) and klass.setSurname(surnminput); to the List but only one value being added even with loops. Is there anyway to add item to a List from class variable?

Scanner input = new Scanner(System.in);
Test klass = new Test("name", "surname");
List < Test > list = new ArrayList < > ();

for (int i = 0; i < 3; i++) {
    String nminput = input.next();
    String surnminput = input.next();
    klass.setName(nminput);
    klass.setSurname(surnminput);
    list.add(klass);
    i++;
}
System.out.println(list);
Mikheil Zhghenti
  • 734
  • 8
  • 28
adam
  • 105
  • 5
  • You seem to be adding the same `Test` instance to your list, multiple times. Perhaps you meant to add multiple `Test` instances instead. – khelwood Oct 05 '20 at 22:27
  • 1
    Also you're incrementing `i` twice each turn through your loop. – khelwood Oct 05 '20 at 22:28
  • Just a question : it is not possible to change exact same object value and added it to the List? – adam Oct 05 '20 at 22:43
  • 1
    That is what you're doing: changing the same object and adding it repeatedly to the list. So you end up with multiple references to the same object in your list. – khelwood Oct 05 '20 at 22:45

1 Answers1

0

Instead of changing the value for the same Test object (it's called Klass) again and again you want to create multiple Test objects inside you're loop.

Scanner input = new Scanner(System.in);
List<Test> list = new ArrayList<>();
for (int i = 0; i < 3; i++) {
    String nminput = input.next();
    String surnminput = input.next();
    Test klass = new Test(nminput, surnminput);
    list.add(klass);
    i++;
}
    System.out.println(list);
magicmn
  • 1,787
  • 7
  • 15
  • Just a question : it is not possible to change exact same object value and added it to the List? – adam Oct 05 '20 at 22:42
  • No because of how objects work in java. In Java when you store a object somewhere, for example in a list, you only store a reference to it. Only the keyword `new` creates a new object which can have different values. – magicmn Oct 05 '20 at 22:48
  • Thanks, now I understand the porblem – adam Oct 05 '20 at 22:48