ArrayList<String> newArray = new ArrayList<String>();
newArray = urlList.getUrl();
for( int i = 0 ; i < newArray.size();i++)
{
System.out.println(newArray.get(i));
}
newArray.toArray(mStrings );// is this correct
mStrings = newArray.toArray();// or this to convert ArrayList ot String array here
for( int i = 0 ; i < mStrings.length;i++)
{
System.out.println(mStrings[i]);
}
EDIT: when i try as below, I get null pointer exception:
try
{
newArray.toArray(mStrings );
for(int i = 0 ; i < mStrings.length; i++)
{
System.out.println(mStrings[i]);
}
} catch( NullPointerException e )
{
System.out.println(e);
}
If you happen to be doing this on Android, there is a nice utility for this called TextUtils which has a . join(String delimiter, Iterable) method. List<String> list = new ArrayList<String>(); list. add("Item 1"); list.
To convert ArrayList to array in Java, we can use the toArray(T[] a) method of the ArrayList class. It will return an array containing all of the elements in this list in the proper order (from first to last element.)
Learn to convert ArrayList to an array using toArray() method. The toArray() method returns an array that contains all elements from the list – in sequence (from first to last element in the list).
add(3); return(numbers); } } public class T{ public static void main(String[] args){ Test t = new Test(); ArrayList<Integer> arr = t. myNumbers(); // You can catch the returned integer arraylist into an arraylist. } }
Usually I write
String[] array = collection.toArray(new String[collection.size()]);
because this way
Collection.toArray(T[])
.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:
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(new Object[0])
Now, If you pass an uninitialized array, you will get a NullPointerException. The best way to do it is:
String[] y = x.toArray(new String[0]);
Please read the document
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With