array.toArray(new String[0])与array.tostring的区别
时间: 2023-06-03 13:04:03 浏览: 58
array.toArray(new String[0])是将数组转换为字符串数组,而array.toString()是将数组转换为字符串表示形式。toArray方法返回的是一个字符串数组,而toString方法返回的是一个代表数组的字符串。其中toArray方法返回的字符串数组可以直接使用,而toString方法返回的字符串需要再次解析才能使用。
相关问题
list.toArray
list.toArray() 是Java中List接口提供的一个方法,用于将List集合转换为数组。这个方法返回一个Object类型的数组,其中包含了List中的所有元素。例如:
```java
List<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("orange");
String[] array = list.toArray(new String[0]);
System.out.println(Arrays.toString(array)); // [apple, banana, orange]
```
在这个例子中,我们将一个包含三个元素的ArrayList转换为一个String类型的数组。注意,我们在toArray()方法中传入了一个空的String数组作为参数,这是因为toArray()方法需要根据传入的数组类型来创建一个新的数组。如果传入的数组长度不足以容纳List中的所有元素,toArray()方法会自动创建一个新的数组来存储所有元素。
string translate to array int use java tool, such as StringUtils or Arrary
You can use the `StringUtils` class from the Apache Commons Lang library to convert a String to an array of integers in Java.
Here's an example code snippet that uses `StringUtils` to convert a String to an array of integers:
```
import org.apache.commons.lang3.StringUtils;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String str = "12345";
int[] arr = StringUtils.toCodePoints(str).toArray();
System.out.println(Arrays.toString(arr)); // Output: [49, 50, 51, 52, 53]
}
}
```
In this code, we first import the `StringUtils` class from the Apache Commons Lang library and the `Arrays` class from the Java standard library.
We then create a String `str` with the value we want to convert to an array of integers. We use the `StringUtils.toCodePoints()` method to convert the String to a stream of Unicode code points, and then use the `toArray()` method to convert the stream to an integer array.
Finally, we use the `Arrays.toString()` method to print the integer array to the console.
Note that the `StringUtils.toCodePoints()` method returns a `IntStream`, so we need to use the `toArray()` method to convert it to an integer array.