[英]Get values from arraylist java?
I have the following class 我有以下课程
public class Patient implements Serializable {
private int id;
private String name;
private String desc;
public Patient(int id, String name, String desc) {
this.id = id;
this.name = name;
this.desc=desc;
}
And then the following getter and setter methods in this class. 然后是此类中的以下getter和setter方法。
Declaring the arraylist 声明数组列表
ArrayList<Patient> list = new ArrayList<Patient>();
Adding run time data in the list 在列表中添加运行时数据
list.add(new Patient(id++, name.getText(), disDesc.getText())
Now i want the read the elements stored in the list How can i do that? 现在我要读取存储在列表中的元素,我该怎么做?
System.out.println(list.get(0));
I use this but it returns the object address of the class 我用它,但它返回类的对象地址
You have to override the toString()
method of Patient
. 您必须重写
Patient
的toString()
方法。 There, you will return all information on the Patient
object that you want to display. 在那里,您将返回要显示的
Patient
对象的所有信息。
Example: (my personal favorite)
示例:(我个人最喜欢的)
private static final String SEPARATOR = ", ";
@Override
public String toString()
{
StringBuilder builder = new StringBuilder();
builder.append("ID: ").append(id).append(SEPARATOR);
builder.append("Name: ").append(name).append(SEPARATOR);
builder.append("Desc: ").append(desc);
return builder.toString();
}
Example 2:
范例2:
@Override
public String toString()
{
return "ID: " + id + ", Name: " + name + ", Desc: " + desc;
}
Example 3:
范例3:
@Override
public String toString()
{
return MessageFormat.format("ID: {0}, Name: {1}, Desc: {2}", id, name, desc);
}
Use either one. 使用其中之一。 It is a matter of preference.
这是一个优先事项。
You have to cast the element, 您必须转换元素,
((Patient) list.get(0)).getName();
And you must add a public getter method to your Patient
class. 并且,您必须在
Patient
类中添加一个公共的getter方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.