public class TestClass{
private String divisions[] ={};
public void doAction(){
Collection testArray = new ArrayList();
// put testArr开发者_StackOverflow社区ay will data
divisions = (String [] ) testArray.toArray(division); //should i use this
divisions = (String [] ) testArray.toArray(new String [] {}); //should i use this?
}
}
if i use case 1, and i call doaction multiple time, the division, something will show wrong records if i use case2, divisions will always show the correct records. is my assumption should use case 2?
Yes, in case 1 you could have a problem with extra items on the end of division. Example: the first time you called doAction and division was set to a certain length then if the next time you called it, it needed less space, there would be extra items that did not get overwritten in the array.
However, case 2 is not all that useful because if the array you pass in (which has a length of zero in your example) is not large enough, ArrayList will just create a new array anyway.
Case 2 is the "more correct" way to use it.
Essentially, you're telling the method what type you would like the resultant array.
Prefer the second one only
divisions = (String [] ) testArray.toArray(new String [] {});
精彩评论