Ansu
Ansu

Reputation: 11

Printing a list of objects only prints their string value

I want to make a lists of objects in Java but when I print the list it contains only the string value:

List<Bucketreturn> list = new ArrayList<Bucketreturn>();            

Bucketreturn br=new Bucketreturn();//creates bucket objects
br.bucket_id=1004;
br.bucket_name=java;
br.item_number=4;
br.date_bucket_added="02-06-2012";
list.add(br);
System.out.println(list);
// prints only string value but I want the integer should also be printed

Upvotes: 1

Views: 1889

Answers (3)

Ashraf
Ashraf

Reputation: 135

Use toString() method for printing all elements of a list by using system.out.println(list.toString())

Upvotes: 1

Polygnome
Polygnome

Reputation: 7820

Override the toString() method in your Bucketreturn class.

list.toString() will print a list of the object in the list, enclosed in '[]' and seprated by ',' using the objects toString() method.

Upvotes: 5

You should override Bucketreturn.toString() and let it return the exact string you want to see.

Something like

  public String toString() {
     return date_bucket_added + " " + bucket_id + " "  + bucket_name + " " + item_number;
   }

If you use Eclipse it has features for helping you easily maintain your toString() methods.

Upvotes: 6

Related Questions