0

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.

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

1
  • Most IDE's such as Eclipse and IntelliJ will be able to automatically generate a toString override for your class. I'd use those, at least as a template. Commented Oct 5, 2013 at 11:39

2 Answers 2

6

You have to override the toString() method of Patient. There, you will return all information on the Patient object that you want to display.

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:

 @Override
 public String toString()
 {
      return "ID: " + id + ", Name: " + name + ", Desc: " + desc;
 }

Example 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.

Sign up to request clarification or add additional context in comments.

5 Comments

Why not just use: return "ID: " + id + " | Name: " + name + " | Desc: " + desc;? Simpler to read IMO, and just as efficient. Alternatively, use String.format.
@JonSkeet From my knowledge, StringBuilder is more efficient than concatenating strings. Am I wrong? I've developed a habit for using StringBuilder.
loved your personal favorite
I believe is everything is on a single command then java is clever and uses string buolder behind the scenes anyway
@RichardTingle That's actually a really good idea for a SO question.
2

You have to cast the element,

((Patient) list.get(0)).getName();

And you must add a public getter method to your Patient class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.