Java implements dynamic arrays

Problem Description:
    1. When learning java, we know that when creating an array, we must determine the size of the array.
    2. But sometimes we don't know the length of the data we want to store.
    3. Of course, people with basic knowledge know that collections can be stored in any length, but sometimes we must use arrays, such as when ResultSetHandler result sets are encapsulated: parameters cannot be placed in collections but only in arrays.

Problem solving: In fact, a list-to-array api has been provided in java. We only need to turn it around. The code is as follows:

 
 
package ziyang; import java.util.ArrayList; import java.util.List; public class List_1 { public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add( "111"); list.add("222"); list.add("333"); //Don't cast when you don't know the data type. Just use Object type String[] array = (String[]) list.toArray(new String[0]);
                //Special attention to this place, be sure to write new String[0] in (), otherwise an error will occur for(int i = 0;i < array.length; i++) { System.out.println(array[i ]); } } }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325819100&siteId=291194637