简体   繁体   中英

Adding arrayList to 2x2 arraylist

I wrote this code to add arraylist to my 2x2 arraylist

ArrayList<ArrayList<String>> addressesAndCores = new ArrayList<ArrayList<String>>();
addressesAndCores.add((new ArrayList<String>().add(remoteIp.getText())));
addressesAndCores.add((new ArrayList<String>().add(remoteIp2.getText())));

However Eclipse gives me the error:

The method add(ArrayList<String>) in the type ArrayList<ArrayList<String>> is not applicable for the arguments (boolean)

It recommends changing add to addall but when I do so it throws this error:

The method addAll(Collection<? extends ArrayList<String>>) in the type ArrayList<ArrayList<String>> is not applicable for the arguments (boolean)

And recommends I change it to add...

Any help would be greatly appreciated

The problem is that the add method of ArrayList does not return the instance (the opposite would be StringBuilder 's append which does return the instance).

The method ArrayList.add will return true if the Collection has changed after performing add .

Therefore you are actually adding boolean to addressesAndCores .

Instead, you can use:

ArrayList<String> toAdd = new ArrayList<String>();
toAdd.add(remoteIp.getText());
addressesAndCores.add(toAdd);

More documentation here:

  • ArrayList add method
  • Collection add method
  • StringBuilder doc

what happened,

you created your list,then you are adding to this list your text new ArrayList<String>().add(remoteIp.getText()) then you are adding to your main list result of this operation instead your list,

and as add() returns boolean and your list expecting ArrayList<String> you have a type mismatch

You cannot do that as several others have pointed out.

I would like to suggest that you create your own builder:

public class ExampleBuilder {

    public static ExampleBuilder newTwoDListBuilder() {
        return new ExampleBuilder();
    }
    private final List<List<String>> underlyingList = new ArrayList<>();

    public ExampleBuilder() {
    }

    public ExampleBuilder add(final List<String> strings) {
        underlyingList.add(strings);
        return this;
    }

    public ExampleBuilder add(final String... strings) {
        underlyingList.add(Arrays.asList(strings));
        return this;
    }

    public List<List<String>> build() {
        return new ArrayList<>(underlyingList);
    }
}

You can then import static it and use it like this:

public static void main(String[] args) throws Exception {
    final List<List<String>> list = newTwoDListBuilder().add("ONE").add("TWO").build();
    System.out.println(list);
}

Output

[[ONE], [TWO]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM