Arraylist provides a convenient toarray method to convert a list into an array. Toarray has two methods for overloading:
1. List. toarray ();
2. List. toarray (T [] );
For the first overload method, the list is directly converted into an array of object;
The second method is to convert the list to the array of the type you need. Of course, when using the list, the list will be converted to the same type as the list content.
If you are not really fond of using the first one, you can write it like this:
1234567 |
ArrayList<String> list= new ArrayList<String>(); for ( int i = 0 ; i < 10 ; i++) { list.add( "" +i); } String[] array= (String[]) list.toArray(); |
Result 1: An error is returned:
Exception in thread "Main" Java. Lang. classcastexception: [ljava. Lang. object; cannot be cast to [ljava. Lang. String;
The reason is clear at first glance. If you cannot convert object [] to string [], you can only retrieve each element and then convert it, as shown in the following code:
12345 |
Object[] arr = list.toArray(); for ( int i = 0 ; i < arr.length; i++) { String e = (String) arr[i]; System.out.println(e); } |
Therefore, the first refactoring method is not so easy.
In fact, when the list world is converted to an array, the second reconstruction method is more convenient. Its usage is as follows:
12 |
String[] array = new String[list.size()]; List. toarray (array); <br> Appendix. source code of the two reconstruction methods: |