Creating an Intstance in an ArrayList
Hi I am supposed to create a class and create a constructor and accessors and mutators. then i must create a program that crates 5 instance objects of the PhoneBook class and stores them in an ArrayList. then use a for loop to display all 4 instances in the Array List.
The Problem i am having is actually hard coding the name and numbers in there and getting them to be displayed. I dont know where to create the instance and how.
Here is my code for Phone Book class
HTML Code:
package Program_4;
public class PhoneBook {
private String name;
private String number;
public PhoneBook() {
name = null;
name = null;
}
public PhoneBook(String phonename, String phonenumber){
name=phonename;
number=phonenumber;
}
public void setname (String phonename){
name=phonename;
}
public String getname(){
return name;
}
public void setnumber (String phonenumber){
number=phonenumber;
}
public String getnumber(){
return number;
}
}
Here is my program
HTML Code:
package Program_4;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class PhoneBookDemo {
public static void main(String[] args) {
PhoneBook book=new PhoneBook();
ArrayList <PhoneBook> entries=new ArrayList<PhoneBook>();
entries.add("Greg","478-454-7605");
entries.add("Peter","478-448-7975");
entries.add("Bob","478-234-7650");
entries.add("John","478-423-7905");
entries.add("Jim","478-124-7235");
for (int x = 0; x < entries.size(); x++){
JOptionPane.showMessageDialog(null, entries.get(x));
}
}
}
Re: Creating an Intstance in an ArrayList
Code :
ArrayList <PhoneBook> entries=new ArrayList<PhoneBook>();
entries.add(new PhoneBook("Greg","478-454-7605"));
entries.add(new PhoneBook("Peter","478-448-7975"));
entries.add(new PhoneBook("Bob","478-234-7650"));
entries.add(new PhoneBook("John","478-423-7905"));
entries.add(new PhoneBook("Jim","478-124-7235"));
Re: Creating an Intstance in an ArrayList
Thank you that did work but everytime i try and print the results in JOPtionPane i get this as a result "Program_4.PhoneBook@863399"
I dont know what this means
Re: Creating an Intstance in an ArrayList
You need to write your own toString method. If you do not your class will inherit the toString method from Object and that is the exact output that method produces.