How to add elements of a string array to a string array list?

JavaArrays

Java Problem Overview


I am trying to pass a string array as an argument to the constructor of Wetland class; I don't understand how to add the elements of string array to the string array list.

import java.util.ArrayList;

public class Wetland {
	private String name;
	private ArrayList<String> species;
	public Wetland(String name, String[] speciesArr) {
		this.name = name;
		for (int i = 0; i < speciesArr.length; i++) {
			species.add(speciesArr[i]);
		}
	}
}

Java Solutions


Solution 1 - Java

You already have built-in method for that: -

List<String> species = Arrays.asList(speciesArr);

NOTE: - You should use List<String> species not ArrayList<String> species.

Arrays.asList returns a different ArrayList -> java.util.Arrays.ArrayList which cannot be typecasted to java.util.ArrayList.

Then you would have to use addAll method, which is not so good. So just use List<String>

NOTE: - The list returned by Arrays.asList is a fixed size list. If you want to add something to the list, you would need to create another list, and use addAll to add elements to it. So, then you would better go with the 2nd way as below: -

    String[] arr = new String[1];
	arr[0] = "rohit";
	List<String> newList = Arrays.asList(arr);
	
	// Will throw `UnsupportedOperationException
    // newList.add("jain"); // Can't do this.
	
	ArrayList<String> updatableList = new ArrayList<String>();
	
	updatableList.addAll(newList); 
	
	updatableList.add("jain"); // OK this is fine. 

    System.out.println(newList);       // Prints [rohit]
	System.out.println(updatableList); //Prints [rohit, jain]

Solution 2 - Java

I prefer this,

List<String> temp = Arrays.asList(speciesArr);
species.addAll(temp);

The reason is Arrays.asList() method will create a fixed sized List. So if you directly store it into species then you will not be able to add any more element, still its not read-only. You can surely edit your items. So take it into temporary list.

Alternative for this is,

Collections.addAll(species, speciesArr);

In this case, you can add, edit, remove your items.

Solution 3 - Java

Thought I'll add this one to the mix:

Collections.addAll(result, preprocessor.preprocess(lines));

This is the change that Intelli recommends.

from the javadocs:

Adds all of the specified elements to the specified collection. Elements to be added may be specified individually or as an array. The behavior of this convenience method is identical to that of c.addAll(Arrays.asList(elements)), but this method is likely to run significantly faster under most implementations.

When elements are specified individually, this method provides a convenient way to add a few elements to an existing collection:

Collections.addAll(flavors, "Peaches 'n Plutonium", "Rocky Racoon");

Solution 4 - Java

You should instantiate your ArrayList before trying to add items:

private List<String> species = new ArrayList<String>();

Solution 5 - Java

Arrays.asList is bridge between Array and collection framework and it returns a fixed size List backed by Array.

species = Arrays.asList(speciesArr);

Solution 6 - Java

In Java 8, the syntax for this simplifies greatly and can be used to accomplish this transformation succinctly.

Do note, you will need to change your field from a concrete implementation to the List interface for this to work smoothly.

public class Wetland {
    private String name;
    private List<String> species;
    public Wetland(String name, String[] speciesArr) {
        this.name = name;
        species = Arrays.stream(speciesArr)
                        .collect(Collectors.toList());
    }
}

Solution 7 - Java

Arrays.asList() method simply returns List type

char [] arr = { 'c','a','t'};    
ArrayList<Character> chars = new ArrayList<Character>();

To add the array into the list, first convert it to list and then call addAll

List arrList = Arrays.asList(arr);
chars.addAll(arrList);

The following line will cause compiler error

chars.addAll(Arrays.asList(arr));

Solution 8 - Java

Arrays.asList is the handy function available in Java to convert an array variable to List or Collection. For better under standing consider the below example:

package com.stackoverflow.works;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Wetland {
	private String name;
	private List<String> species = new ArrayList<String>();
	
	public Wetland(String name, String[] speciesArr) {
		this.name = name;
		this.species = Arrays.asList(speciesArr);
	}
	
	public void display() {
		System.out.println("Name: " + name);
		System.out.println("Elements in the List");
		System.out.println("********************");
		for (String string : species) {
			System.out.println(string);
		}
	}
	
	/*
	 * @Description: Method to test your code
	 */
	public static void main(String[] args) {
		String name = "Colors";
		String speciesArr[] = new String [] {"red", "blue", "green"};
		Wetland wetland = new Wetland(name, speciesArr);
		wetland.display();
	}

}

Output:

enter image description here

Solution 9 - Java

ArrayList<String> arraylist= new ArrayList<String>();

arraylist.addAll( Arrays.asList("mp3 radio", "presvlake", "dizalica", "sijelice", "brisaci farova", "neonke", "ratkape", "kuka", "trokut")); 

Solution 10 - Java

Use asList() method. From java Doc asList

List<String> species = Arrays.asList(speciesArr);

Solution 11 - Java

public class duplicateArrayList {

	
	ArrayList al = new ArrayList();
	public duplicateArrayList(Object[] obj) {
	
		for (int i = 0; i < obj.length; i++) {
			
			al.add(obj[i]);
		}
		
		Iterator iter = al.iterator();
		while(iter.hasNext()){
			
			System.out.print(" "+iter.next());
		}
	}
	
	public static void main(String[] args) {

		
	String[] str = {"A","B","C","D"};
	
	duplicateArrayList dd = new duplicateArrayList(str);
		
	}

}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionrobinhood91View Question on Stackoverflow
Solution 1 - JavaRohit JainView Answer on Stackoverflow
Solution 2 - JavaRavi AView Answer on Stackoverflow
Solution 3 - JavakeisarView Answer on Stackoverflow
Solution 4 - JavaJens PiegsaView Answer on Stackoverflow
Solution 5 - JavaSubhrajyoti MajumderView Answer on Stackoverflow
Solution 6 - JavaMakotoView Answer on Stackoverflow
Solution 7 - JavawebjockeyView Answer on Stackoverflow
Solution 8 - Java1218985View Answer on Stackoverflow
Solution 9 - JavapikardttView Answer on Stackoverflow
Solution 10 - JavaSumit SinghView Answer on Stackoverflow
Solution 11 - JavadnyaneshwarView Answer on Stackoverflow