Why do I keep getting only tha last object value in Java ArrayList?

前端 未结 2 1975
你的背包
你的背包 2020-12-22 14:24

I have managed to put all objects into arraylist but I am not able to print all values. Only the last one is getting printed, regardless of method used.

It is not g

相关标签:
2条回答
  • 2020-12-22 14:58

    You have two errors :

    1. You are adding the same Player1 instance to the list over and over again. You should move Player1 user = new Player1(); into the loop that adds the players.

      Change

      Player1 user = new Player1();
      
      // Tokenizing
      System.out.println("CSCI213 Players Management System");
      while (input.hasNextLine()) {
      

      to

      // Tokenizing
      System.out.println("CSCI213 Players Management System");
      while (input.hasNextLine()) {
          Player1 user = new Player1();
      
    2. The members of the Player1 class are all static, so even if you fix the first issue, all instances of Player1 will share these members. You should change them to non static.

      Change

      public class Player1 {
          static String loginname;
          static String password;
          static String chips;
          static String username;
          static String email;
          static String birthdate;
      

      to

      public class Player1 {
          String loginname;
          String password;
          String chips;
          String username;
          String email;
          String birthdate;
      
    0 讨论(0)
  • 2020-12-22 15:06

    Simple:

     Player1 user = new Player1();
    

    You are adding the same object again and again. Put that statement into your loop instead. You want to add a completely new Playwer object during each loop iteration!

    But even then, things wouldn't work out; because (as Eran figured): your Player class has only static fields. That is like "cheating"; because it means that all Player objects would see the same fields, too (because static fields are shared between all instances of a class!)

    In other words: static is an abnormality in good OO design. You don't use it as default; to the contrary: you only make fields static in special corner cases (see here for some examples).

    0 讨论(0)
提交回复
热议问题