72

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]);
        }
    }
}
0

10 Answers 10

120

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]
Sign up to request clarification or add additional context in comments.

10 Comments

@rorrohprog.. It doesn't returns Object, but a List<T>, where T is the type of array you pass. See docs.oracle.com/javase/7/docs/api/java/util/…
@rorrohprog. I think you should try this code. And see the docs I gave the link..
@RohitJain You cannot cast from java.util.Arrays.ArrayList (result from Arrays.asList() to java.util.ArrayList.
@maba. Yeah edited the post. ArrayList returned is different in asList method.
It shall be noted that Collections.addAll() is a preferred method: 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. (Javadoc)
|
18

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.

Comments

13

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
<tt>c.addAll(Arrays.asList(elements))</tt>, 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:
<pre>
Collections.addAll(flavors, "Peaches 'n Plutonium", "Rocky Racoon");
</pre>

Comments

6

You should instantiate your ArrayList before trying to add items:

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

1 Comment

That isn't really what the question is asking.
5

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

species = Arrays.asList(speciesArr);

3 Comments

Arrays.asList returns an object!
@rorrohprog If you read the docs docs.oracle.com/javase/6/docs/api/java/util/… it says it returns List<T>
@rorrohprog, Why doesn't it compile? I have it compiling? The only reason I could see this not compiling is if you were using the wrong Arrays or List classes.
3

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());
    }
}

Comments

3

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));

Comments

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

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

Comments

1

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

Comments

-3
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);

    }

}

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.