user2904400 user2904400 - 17 days ago 5
Java Question

Update ArrayList by passing argument in Java

I am trying to up create and update an

ArrayList
by passing an argument, so that I will end up with a list of say 10 names; however, the current function doesn't seem to be working - any ideas pls?

public String addClient(String name) {
ArrayList<String> myList = new ArrayList<String>();
myList.add(name);

return myList;
}

Answer

This is what you need to do:

ArrayList<String> myList = new ArrayList<String>();

public void addClient(String name) {
    myList.add(name);
}

If you create a list inside the method, it will only have one value, and will go away once method execution finishes (unless it's returned). Have a look at different scopes here. You should create a list at a class level and add the elements into it.

Also, method does not need to return anything, so it's better to change the type to void.