How to put user defined Object in Collection ?

see this example:
import java.util.*;
class Address
{
String name;
int age;
String city;
Address(String name,int age,String city){
this.name=name;
this.age=age;
this.city=city;}
public String toString(){
return "name:"+name+"\tage:"+age+"\tcity:"+city+"\n";
}
};
class demo
{
public static void main(String[] args){
ArrayList
al=new ArrayList
();
Address add1=new Address("bhabani",24,"blore");
Address add2=new Address("mahesh",23,"kolkata");
Address add3=new Address("pinku",22,"bbsr");
Address add4=new Address("chary",24,"chennai");
al.add(add1);
al.add(add2);
al.add(add3);
al.add(add4);
System.out.println(al);
}};
Here if we do not override the toString() then we will get output like this.
Address@7666 Address@21334 Address@76757 Address@34356.
Because by default it calls the toString() of AbstractCollection.

No comments:

Post a Comment