user3462940
user3462940

Reputation: 59

adding elements in a list to another list

First I have two strings.

String name = "my name is";
String address = "my address is";

Then I want to split the 'name' string value from the space character and add to a list.

List word_list = new ArrayList();
word_list.add(Arrays.asList(name.split(" ")));

Then similarly I want to split the 'address' string value and add to the same 'word_list'.

word_list.add(Arrays.asList(address.split(" ")));

From this finally what I get is,

[[my, name, is],  [my, address, is]]

But what I want is,

[my, name, is, my, address, is]

Is there any shorter method other than writing a loop to solve this problem?

Upvotes: 0

Views: 85

Answers (3)

Mena
Mena

Reputation: 48404

There are two issues in your code.

  • Your word_list is not generic. You should declare and initialize it as:

List<String> word_list = new ArrayList<String>();

... or optionally use the diamond syntax from Java 7 on:

List<String> word_list = new ArrayList<>();

This way, you ensure type safety, as in, compile-time checks on what gets in (we want Strings).

  • Since your List is not generic, it will take any Object. In this case, you are adding a List<String>, not a String

Instead, use word_list.addAll(Arrays.asList(name.split(" ")))

Upvotes: 0

Carles
Carles

Reputation: 186

There's a function that does what you want:

public String[] mergeArrays(String[] mainArray, String[] addArray) {
    String[] finalArray = new String[mainArray.length + addArray.length];
    System.arraycopy(mainArray, 0, finalArray, 0, mainArray.length);
    System.arraycopy(addArray, 0, finalArray, mainArray.length, addArray.length);

    return finalArray;
}

By the way, Apache Commons Lang Lib has a one-line function to do that:

[ArrayUtils.addAll(T\[\], T...)][1]

Upvotes: 0

Eran
Eran

Reputation: 393781

You need addAll :

word_list.addAll(Arrays.asList(name.split(" ")));
word_list.addAll(Arrays.asList(address.split(" ")));

add treats the argument as a single element to be added to the list. addAll expects a Collection of elements to be added to the list.

BTW, if you defined your list as List<String> word_list = new ArrayList<String>();, the compiler would have prevented you from calling add with a List as an argument.

Upvotes: 2

Related Questions