java中arraylist中存储实体对象如何转换成字符串数组
时间: 2024-05-01 13:22:40 浏览: 94
假设你的实体类为 `Person`,其中包含属性 `name` 和 `age`,你想把 `ArrayList<Person>` 转换成字符串数组,可以按照以下步骤进行:
1. 创建一个空的字符串数组,长度为 `ArrayList` 的大小。
```java
String[] strArray = new String[arrayList.size()];
```
2. 遍历 `ArrayList`,将每个 `Person` 对象转换成字符串,并存入字符串数组中。
```java
for (int i = 0; i < arrayList.size(); i++) {
Person person = arrayList.get(i);
String str = person.getName() + "," + person.getAge();
strArray[i] = str;
}
```
完整代码如下:
```java
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Person> arrayList = new ArrayList<>();
arrayList.add(new Person("张三", 20));
arrayList.add(new Person("李四", 25));
arrayList.add(new Person("王五", 30));
String[] strArray = new String[arrayList.size()];
for (int i = 0; i < arrayList.size(); i++) {
Person person = arrayList.get(i);
String str = person.getName() + "," + person.getAge();
strArray[i] = str;
}
// 输出字符串数组
for (String str : strArray) {
System.out.println(str);
}
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
```
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)