gpt4 book ai didi

java - 如何将对象的一个​​元素转换为实例数组?

转载 作者:行者123 更新时间:2023-12-01 17:10:39 25 4
gpt4 key购买 nike

我有这个类People,其中包含字段名称、电话、电子邮件和地址。这个类有很多实例。如何获取名称元素的所有实例的数组。例如,字符串[]数组=“约翰,蒂姆,哈利”。因此,我想做的就是从每个实例中取出一个元素并创建一个数组。我已经为此工作了很长时间。非常感谢您的帮助。顺便说一句,所有字段都是字符串。

最佳答案

1-创建人员模型

public class People {
private String name;
private String phone;
private String address;
public People(String name, String phone, String address) {
this.name = name;
this.phone = phone;
this.address = address;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the phone
*/
public String getPhone() {
return phone;
}
/**
* @param phone the phone to set
*/
public void setPhone(String phone) {
this.phone = phone;
}
/**
* @return the address
*/
public String getAddress() {
return address;
}
/**
* @param address the address to set
*/
public void setAddress(String address) {
this.address = address;
}

}

2-创建自定义适配器

public class PeopleListAdapter extends BaseAdapter {

private Context context;
private ArrayList<People> peopleItems;

public PeopleListAdapter(Context context,
ArrayList<People> peopleItems) {
this.context = context;
this.peopleItems = peopleItems;
}

@Override
public int getCount() {
return peopleItems.size();
}

@Override
public Object getItem(int position) {
return peopleItems.get(position);
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.people_list_item, null);
}
// TODO
/**
* Return some list row..
*/
TextView nameTxt = (TextView) convertView.findViewById(R.id.name);
TextView phoneTxt = (TextView) convertView.findViewById(R.id.phone);
TextView addressTxt = (TextView) convertView.findViewById(R.id.address);

nameTxt.setText(peopleItems.get(position).getName());
phoneTxt.setText(peopleItems.get(position).getPhone());
phoneTxt.setText(peopleItems.get(position).getAddress());

return convertView;
}

}

更新

private ArrayList<People> peopleList = new ArrayList<People>();
peopleList.add(new People("name1", "phone1","address1");
peopleList.add(new People("name2", "phone2","address2");

// adaptor
PeopleListAdapter adaptor = new PeopleListAdapter(getApplicationContext(),peopleList);
//some list view
listView.setAdapter(adapter);

关于java - 如何将对象的一个​​元素转换为实例数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23922568/

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