This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
But I'm just wondering why my first code does not work whereas I declare my arrayList as String. I know I'm missing something here. Please help.
Look at the API.
toArray() returns an Object. This is created as an Object, not a String. Therefore, you cannot cast it to String.
toArray(T) returns a T (for whatever T you want). So if you want toArray to return a String, you need this version and pass it any String array. Performance dictates that you should use either an array that will be large enough for all elements (so using the collection size is good) or a cached version of an empty array. This is because if the passed array is not large enough a new array will be created. Imagine creating an array for the sake of getting the right type of array, then having another array be created within toArray. Either skip the creation of the passed array (cached empty array) or the creation within toArray (by passing an array that is large enough).