Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Adding List<String> from parameter to existing list

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.

like image 875
Dembele Avatar asked Mar 17 '13 12:03

Dembele


2 Answers

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"));
like image 70
Ivan Borisov Avatar answered Sep 19 '22 12:09

Ivan Borisov


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 -

  1. You need an existing list - it can't be with the name of the list in the parameter. Let's call it existingList.
  2. After you get the list in the method, you shouldn't use the "new ArralyList" on it, as it will void the list from the parameter.

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);
like image 34
Issahar Weiss Avatar answered Sep 21 '22 12:09

Issahar Weiss