Reputation: 31
When I try to use print line to see my array list, the way it's getting printed is not how I want it to be. What do I need to change to receive just the name?
This is how I am adding a new contact:
public class ContactGroup
{
ArrayList<Contact> contactList= new ArrayList<Contact>();
Public void addContact(String aCName)
{
Contact contact= new Contact(aCName);
contactList.add(contact);
}
public class Contact
{
private String name;
public Contact(String aCName)
{
super();
this.name = aCName;
}
}
Upvotes: 1
Views: 93
Reputation: 43
You can override the toString() method in any object class
@Override
public String toString(){return "My Text to display";}
Upvotes: 1
Reputation: 1435
you should add a toString() implementation to Contact class
public class Contact{
private String Name;
public Contact(String name){
this.Name=name;
}
// add toString method here
@Override
public String toString(){
return "This is a Contact of :"+this.Name;
}
}
Upvotes: 0
Reputation: 4605
You need to implement toString() method inside your class containing the ArrayList. Please follow the best practices suggested in EffectiveJava while implementing the toString() method.
Upvotes: 0
Reputation: 4516
Override toString() method in your class Contact
public class Contact
{
private String name;
public Contact(String aCName)
{
super();
this.name = aCName;
}
@Override
public String toString()
{
return "contact name " + this.name; //say you want to print the name property
}
}
Upvotes: 0
Reputation: 24177
public static void main(String[] args) {
List<Contact> contactList= new ArrayList<Contact>();
// code to insert contact in list
for(Contact contact : contactList) {
System.out.println(contact.getName());
}
}
Did you try this to print name only? Another option is to override toString()
method as:
public class Contact {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Contact(String name) {
this.name = name;
}
@Override
public String toString() {
return "Contact{" +
"name='" + name + '\'' +
'}';
}
}
And then use it as:
public static void main(String[] args) {
List<Contact> contactList= new ArrayList<Contact>();
// code to insert contact in list
for(Contact contact : contactList) {
System.out.println(contact);
}
}
Upvotes: 3