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]);
        }
    }
}
Jens Piegsa
  • 7,399
  • 5
  • 58
  • 106
robinhood91
  • 1,641
  • 3
  • 20
  • 36

10 Answers10

117

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]
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • 2
    @rorrohprog.. It doesn't returns Object, but a List, where T is the type of array you pass. See http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#asList(T...) – Rohit Jain Oct 12 '12 at 06:48
  • 1
    @rorrohprog. I think you should try this code. And see the docs I gave the link.. – Rohit Jain Oct 12 '12 at 06:51
  • @RohitJain You cannot cast from `java.util.Arrays.ArrayList` (result from `Arrays.asList()` to `java.util.ArrayList`. – maba Oct 12 '12 at 07:02
  • @maba. Yeah edited the post. `ArrayList` returned is different in `asList` method. – Rohit Jain Oct 12 '12 at 07:03
  • @RohitJain But as per your way, after storing elements to species, user will not be able to add() or remove() any element. Better to store it in some temp list then add that to species. – Ravi A Oct 12 '12 at 09:45
  • @RaviAmlani.. Yeah, the list returned by `Arrays.asList` is a fixed sized list.. To add anything, we need to get a newlist with `addAll` method. – Rohit Jain Oct 12 '12 at 09:59
  • @RohitJain same thing I've already mentioned in my answer. no one had pointed it out...still no vote ups. :) – Ravi A Oct 12 '12 at 11:52
  • 11
    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) – berezovskyi Aug 06 '14 at 09:21
  • suppose that our new string array is arry2 and our string list, which we want to add arry2 is list1.then we can add array (arry2) to string list (list1) like this,,,,,,,,,,,,, list1.addAll(Arrays.asList(arry2)); – naseer mohammad Feb 12 '17 at 16:57
  • This line should be changed to List species = Arrays.asList(speciesArr); – webjockey May 15 '17 at 15:45
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.

Ravi A
  • 505
  • 1
  • 5
  • 16
12

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>
keisar
  • 5,266
  • 5
  • 28
  • 28
7

You should instantiate your ArrayList before trying to add items:

private List<String> species = new ArrayList<String>();
Jens Piegsa
  • 7,399
  • 5
  • 58
  • 106
6

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

species = Arrays.asList(speciesArr);
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
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());
    }
}
Makoto
  • 104,088
  • 27
  • 192
  • 230
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));
Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
webjockey
  • 1,647
  • 2
  • 20
  • 28
2
ArrayList<String> arraylist= new ArrayList<String>();

arraylist.addAll( Arrays.asList("mp3 radio", "presvlake", "dizalica", "sijelice", "brisaci farova", "neonke", "ratkape", "kuka", "trokut")); 
Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
pikardtt
  • 29
  • 1
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

1218985
  • 7,531
  • 2
  • 25
  • 31
-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);

    }

}
TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
  • [What is a raw type and why shouldn't we use it?](https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it) – luk2302 Mar 09 '22 at 09:42