AboutArtemus Harper Expertise I have a BS in computer science and am working towards a Masters degree.
Experience I have experience in Core Java, good background in Java swing/gui, some experience with JNI, Java reflection, and Java java.nio.*
knowledge of Java bytecode and annotations.
Basics in c++ and c#
Expert: Artemus Harper Date: 5/22/2008 Subject: Printing objects from an arrayList
Question I am having problems printing the content of my objects that are in my arrayList. What I have now prints the address instead of the content. This is the code I have:
import javax.swing.JOptionPane;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
public class CustomerTest
{
public static void main(String[] args)
{
String name;
int zip;
long creditCard;
short ccid;
ArrayList<Customer> CustList = new ArrayList<Customer>();
Customer myCust = null;
name = JOptionPane.showInputDialog(null,
"Enter your name");
zip = Integer.parseInt(JOptionPane.showInputDialog(null,
"Enter your zip code"));
creditCard = Long.parseLong(JOptionPane.showInputDialog(null,
"Enter your credit card number"));
ccid = Short.parseShort(JOptionPane.showInputDialog(null,
"Enter your CCID number found on the back of your card"));
myCust = new Customer(name, zip, creditCard, ccid);
CustList.add(myCust);
DisplayArrayList("Customer", CustList);
}
public static void DisplayArrayList(String name, ArrayList list)
{
String output = name + "\n";
for(int index=0; index<list.size(); index++)
{
Customer c = (Customer)list.get(index);
JOptionPane.showMessageDialog(null, c);
}
}
}
Answer If its just printing the customer's address, then you will need to fix the toString() method in the Customer class to print its entire contents instead of just the address.
Also as you have it now a separate dialog box will appear for each customer.
If you want a method that displays a customer given a name, you should store the customers in a map (e.g. HashMap) instead of a list.
E.g. (if toString is fixed in Customer):
...
HashMap<String,Customer> customers = new HashMap<String, Customer>();
...
customers.put(myCust.getName(),myCust);
...