Taylor Mudd Taylor Mudd - 8 months ago 31
Java Question

Access object constructor created ArrayList Java

I'm working on a project where I need to create an ArrayList inside the constructor of a class. I have done this as so:

ArrayList<Users> grouping;
public userGroup(){
grouping = new ArrayList<Users>();

This is working as intended.
I declared a new userGroup administrators in my 'Main.java'

userGroup administrators = new userGroup();

However I now need to access the ArrayList from Main.java,
like this:

/*Last Item in administrators Object's ArrayList*/.setUserType("user");

I'm not sure how to do this..
I have tried


But don't know what to try next.


administrators.grouping will give you the list. if you want to access an element from it, you need to get it first, and only then you can call setUserType on it.


where i is the index of the element you want from the list.

Also- it's good practice to encapsulate the fields of your class, i.e. don't access the field directly but set them as private and add a getter method:

public class UserGroup {
 private List<Users> grouping;
 public userGroup(){
  grouping = new ArrayList<Users>();      
 public ArrayList<Users> getGrouping() {
  return this.groupingl

And then: