arraylist toarray
时间: 2023-07-14 07:02:22 浏览: 96
arraylist .
Sure! To convert an ArrayList to an array in Java, you can use the `toArray()` method. Here's an example:
```java
import java.util.ArrayList;
public class ArrayListToArrayExample {
public static void main(String[] args) {
// Create an ArrayList
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("Hello");
arrayList.add("World");
arrayList.add("!");
// Convert ArrayList to array
String[] array = arrayList.toArray(new String[arrayList.size()]);
// Print the elements of the array
for (String element : array) {
System.out.println(element);
}
}
}
```
In this example, we create an ArrayList of strings (`arrayList`) and add some elements to it. Then, we use the `toArray()` method to convert the ArrayList to an array. The `toArray()` method requires an array of the desired type as an argument, so we pass in a new String array with the same size as the ArrayList. Finally, we iterate over the elements of the array and print them out.
Hope this helps! Let me know if you have any more questions.
阅读全文