I want to be able to add new entries of parameter inputs to the list.
For example:
public static void theList (List<String> wholeList) {
wholeList = new ArrayList<String>();
wholeList.add("Lettuce");
wholeList.add("Bacon");
wholeList.add("Milk");
wholeList.add(wholeList); <--------- error - addAll doesn't fix it.
Above I tried ' wholeList.add(wholeList) '. What I intended to do is: Whatever additional (item (from parameter), when adding the input to run this method) item I need to add, will be added to the ' wholeList '.
As you can see, I have 3 items added to the list: Lettuce, Bacon and Milk. However, if I suddenly changed my mind, and want to add another item (via parameter), I can simply add it to the current list (wholeList).
Also, another question.
Is there a neater way to add a list of items instead of adding it one-by-one (whilst using the same list import)? Say, {"Lettuce", "Milk", "Bacon", etc}?
TY.
As I understand, addAll()
is everything you need:
List<String> someList = new ArrayList<String>();
List<String> itemsToAdd = new ArrayList<String>();
itemsToAdd.add("one");
itemsToAdd.add("two");
someList.addAll(itemsToAdd);
// or use handy method which creates temporary list internally:
someList.addAll(Arrays.asList("three", "four"));
Well, your code does something very wrong. You initialize the wholeList inside the method, and after the method is finished, it is gone (pointers in Java). Also, you added the list on itself, so the code is probably not what you wanted to do.
you probably meant to create a new list inside the method and add all the items to the list in the parameter. If so, you shouldn't use "new" on the list that you got from a parameter.
Actually, after reading the title of your question -
Your code should look like that:
public static void theList (List<String> wholeList) {
wholeList.add("Lettuce");
wholeList.add("Bacon");
wholeList.add("Milk");
existingList.add(wholeList);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With