Skip to content Skip to sidebar Skip to footer

Arraylist To Array Of Strings In Java

ArrayList newArray = new ArrayList(); newArray = urlList.getUrl(); for( int i = 0 ; i < newArray.size();i++) { System.out.println(newArray.get(i)

Solution 1:

Usually I write

String[] array = collection.toArray(newString[collection.size()]);

because this way

  1. I get an array of the type that I want.
  2. I don't have to declare the array before calling Collection.toArray(T[]).

Solution 2:

Depends on what you want to do. Both are correct

toArray() Returns an array containing all of the elements in this list in proper sequence (from first to last element).

Refer here

toArray(T[] a) Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array. If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list.

Refer here

In former, you want to get an array. In latter you have an array, you just wanted to fill it up.

In your case, first form is preferred as you just want to get an array without bothering size or details.


Basically this is what happens in 2nd case:

  1. List's size is measures.
  2. (a) If list size is less than that of the array provided, new Array of the type provided as argument is created.(b)Else, the list is dumped in the specified array.

The only benefit of doing so, is you avoid casting. The two form are the same. If you use Object array. i.e.

     myList.toArray() <==> toArray(newObject[0])

Now, If you pass an uninitialized array, you will get a NullPointerException. The best way to do it is:

String[] y = x.toArray(newString[0]);

Please read the document

Solution 3:

The first option is better as it allows you to pass in a typed array, which is then populated inside the method.

The second option returns an Object[] - so you would have to cast it to use String methods.

Solution 4:

In plain java i'm use something like

rolesList.toArray(newInteger[rolesList.size()]);

for converting list to array. Don't know in android.

Solution 5:

How about this

 List a = new ArrayList();
   a.add("wer");
   a.add("sff");
   String[] f= (String[]) a.toArray(new String[0]);
   System.out.println(f[0]);

Post a Comment for "Arraylist To Array Of Strings In Java"