2

I have a Matchmaker class which initializes an ArrayList to store objects of my user class.

    //Class which keeps user objects in its ArrayList called Database
    MatchMaker myData = new MatchMaker();

    //My user object
    user tempUser;

    ArrayList<String> emails = new ArrayList<String>();
    emails = JSONRead.read();

    //Create a user at every loop, initialized by a email (String):
    for (int i = 0; i < emails.size(); i++) {

        tempUser = new user(emails.get(i));
        myData.Database.add(tempUser);
        System.out.println("User at position " + i + ": " + myData.Database.get(i).get("Firstname"));
    }

The result in this loop is:

User at position 0: Luat
User at position 1: Pim

Outside that loop I try print every object which should be in my ArrayList:

    //Print out every user in my ArrayList
    for(int i = 0 ; i < myData.Database.size() ; i ++){
        System.out.println("User at position " + i + ": " +m yData.Database.get(i).get("Firstname"));
    }

The result in this loop is:

User at position 0: Pim
User at position 1: Pim

What is the problem here, it seems the last object which was added is duplicated throughout my ArrayList? State if I must post more information about my user class.

Zimbabaluba
  • 588
  • 1
  • 8
  • 24
  • 1
    Check to make sure that the fields in your user class are not static. – azurefrog Jan 07 '16 at 21:07
  • They are static, I have read in other questions that this can cause a problem? – Zimbabaluba Jan 07 '16 at 21:08
  • Yes, static fields are for data which is not related to any particular object. See: [what is the meaning of static fields](http://stackoverflow.com/questions/797964/what-is-the-exact-meaning-of-static-fields-in-java) – azurefrog Jan 07 '16 at 21:09
  • In this particular situation, since your name field is static, it means that all users have the same name. – azurefrog Jan 07 '16 at 21:10
  • So you recommend I change all my fields to private? Which does make some things tricky – Zimbabaluba Jan 07 '16 at 21:12
  • Add getters and setters to access your new private fields - this is the 'norm' for Java objects and should solve most of your problems. – Jason Jan 07 '16 at 21:24
  • The scope of a variable is unrelated to whether or not it's static. You can have public static or private static variables. Without seeing what your User class look like, it's difficult to say what it *should* look like. – azurefrog Jan 07 '16 at 21:25
  • Ok thanks for all advice, indeed its problems related with my variables being static, I changed everything a bit (from being static) and it works now. – Zimbabaluba Jan 07 '16 at 21:36

0 Answers0