Adding elements to a array list/Pojo

I am having issue in adding elements to a Arraylist. I created a POJO like my array list.

public class GroupUserMapping {
    String group;
    ArrayList<String> users;
//setters getters constructor
}

I have function where I am reading a text file to get Groups which I stored in groups array now for those groups I need to loop through all the records in other text file and get all the users which has this group mapping and according to my condition I am trying to add elements to the Pojo arraylist like this:

 ArrayList<GroupUserMapping> usergroups = new ArrayList< GroupUserMapping >();
        ArrayList<String> users = new ArrayList<>();
        ArrayList<String> groups = getGroups();// This used for lopping I have certain groups.
        Scanner s = null;

        String group="";
       for(int i= 0;i<groups.size();i++ ){
           s = new Scanner(new File(getClass().getClassLoader().getResource(mappingFile).getFile()));
           s.useDelimiter("rn");
           group=groups.get(i);
           users.clear();
           while (s.hasNext()) {
               String aLine = s.next();
               String[] value = aLine.split(":");

               if(group.equalsIgnoreCase(value[0]))
               {
                   LOGGER.info(group+":"+value[1]);
                   users.add(value[1]);
               }
           }
            GroupUserMapping groupUserMapping = new GroupUserMapping(group,users);
          
            usergroups.add(groupUserMapping);
           s.close();

Issue is when I am reading for Group say G1 I got users u1,u2 and these mapping is correctly stored in usergroups but next loop when I am searching for Group G2 I have users U2,U3. Here in the 2nd loop it is also updating 1st Group values as well. Ideally my elements should be G1->U1,U2 and G2-> U2,U3 but my code is adding elements like this. G1->U2,U3 G2-> U2,U3. What I am doing wrong here? Please help

Answer

The line users.clear(); is causing the issue.

In the first iteration you add users 1 and 2 to that list. Then in the constructor you are passing this list.

GroupUserMapping groupUserMapping = new GroupUserMapping(group,users);

Now in the second iteration, you clear the loop and then add users 2 and 3. Since the first group has the reference to the same list, G1’s user list is also cleared and user 2 and 3 are added.

You need to replace the users.clear(); with

users = new ArrayList<String>();

In the above case, the data is unchanged, only the users variable now points to a different location. Hence there won’t be any changes to the list of G1.