gpt4 book ai didi

java - 使用类将 arraylist 添加到数组适配器

转载 作者:行者123 更新时间:2023-12-02 02:58:26 25 4
gpt4 key购买 nike

我无法弄清楚如何从使用类的数组列表中添加信息,以及如何将信息添加到 ListView 中的数组适配器。我正在尝试添加此数组中的名字。

我怎样才能做到这一点?

我有这个单独的类(不确定 toString 是否正确):

public class PersonClass {

final private String firstName;
final private String lastName;
final private String birthday;
final private int personPic;

private PersonClass(String fName, String lName, String bDay, int pic) {

firstName = fName;
lastName = lName;
birthday = bDay;
personPic = pic;

}

public String toString() {
return firstName+" "+lastName+" "+birthday+" "+personPic;
}

public static void main(String args[]){

// Information for each person using the PersonClass
PersonClass person1 = new PersonClass("first name", "last name", "01/01/2000", R.drawable.pic1);
// ..... up to 10...


// ArrayList
final ArrayList<PersonClass> personList = new ArrayList<>();

// Add person data to array list
personList.add(person1);
personList.add(person2);
personList.add(person3);
personList.add(person4);
personList.add(person5);
personList.add(person6);
personList.add(person7);
personList.add(person8);
personList.add(person9);
personList.add(person10);

}

}

这是我的阵列适配器。

final ArrayAdapter<String> arrayAd = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,???);

我不能只将数组列表名称添加到适配器中,因为数组有一个类向其添加信息。但我只想在 ListView 上显示数组的第一个名称。

最佳答案

import java.util.ArrayList;
import java.util.List;

class Person {
private String firstName;

//Might be more fields

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public Person(String firstName) {
super();
this.firstName = firstName;
}

}

public class SO1 {

public static void main(String[] args) {

List<Person> personList = new ArrayList<Person>();
//Either you can directly add first name in adaptor
for (int i = 0; i < 10; i++) {
personList.add(new Person("Name "+i));
}

//If you have list than you have to iterate it and add first name
List<String> adaptorList = new ArrayList<String>();
personList.forEach( p -> adaptorList.add(p.getFirstName()));

System.out.println(adaptorList);
}

}

关于java - 使用类将 arraylist 添加到数组适配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42730552/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com