user3001764
user3001764

Reputation: 31

How to create an ArrayList that I can add items too like this Java

I have the following String list which is constructed as:

String[] messageList = messages.split("(?<=\\G.{" + 9 + "})");

I want to be able to add new strings to the list but of course this would need to be an arraylist.

How could I make an array list from this string list?

Thanks

Upvotes: 2

Views: 153

Answers (4)

Alexis C.
Alexis C.

Reputation: 93872

You can use Arrays.#asList(T...) to construct a new ArrayList containing the elements in the messageList array.

Before Java 7 :

List<String> l = new ArrayList<String>(Arrays.asList(messageList));

After :

List<String> l = new ArrayList<>(Arrays.asList(messageList));

Or directly :

List<String> l = new ArrayList<>(Arrays.asList(messages.split("(?<=\\G.{" + 9 + "})")));

Upvotes: 3

Sandhu Santhakumar
Sandhu Santhakumar

Reputation: 1688

List<String> lst = new ArrayList<>(Arrays.asList(messages.split("(?<=\\G.{" + 9 + "})")));

Upvotes: 2

Rahul Tripathi
Rahul Tripathi

Reputation: 172558

Try this:

List<String> lst = new ArrayList<>(Arrays.asList(messageList));

or:

List<String> lst = new ArrayList<>(Arrays.asList(message.split("(?<=\\G.{" + 9 + "})")));

Also check Arrays.asList

Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.) This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray(). The returned list is serializable and implements RandomAccess.

Upvotes: 2

Masudul
Masudul

Reputation: 21971

Use Arrays#asList. Try,

List<String> list= new ArrayList<>(Arrays.asList(messageList));

Upvotes: 3

Related Questions