Offset Null Entertainment, LLC Software and Graphic Design Solutions


Turn an ArrayList into an Array

In Java and Android, Arrays have a fixed length. Coming from Perl and PHP where arrays can grow and shrink without needing to be redefined, this concept presented challenges while defining arrays. Enter the ArrayList. Unlike Java's and Android's Arrays, whose size doesn't change, you can add or remove elements in an ArrayList dynamically.

However, several of the methods I'm using require Arrays and not ArrayLists. You may also want to convert an ArrayList to an Array because some operations can be faster with an Array. Fortunately, there's a simple call that will convert an ArrayList to an Array, here's how:

ArrayList myArrayList = new ArrayList(); // Define your ArrayList. In this case, I created an ArrayList of strings.

myArrayList.add("Android"); // Dynamically adds an element
myArrayList.remove("C#"); // Removes the "C#" element from myArrayList

String[] targetArray = new String[myArrayList.size()];
myArrayList.toArray(targetArray); // Converts myArrayList to the array, targetArray

In the above example, the .toArray() ArrayList method converts myArrayList to the array of strings, targetArray. Now you're free to pass targetArray to a method requiring an array of strings or take advantage of the better performance that Arrays can offer.

Pretty easy, huh?

Comments (0) Trackbacks (0)

Sorry, the comment form is closed at this time.

No trackbacks yet.