3D-kreativ
3D-kreativ

Reputation: 9301

List values from objects methods that are in an arraylist of objects?

I'm learning Java programming and right now I'm exploring the use of objects in arralist. I know how to get a single value out of a object that are in a arraylist like this:

customerList.get(0).getAccountOwnerName()

EDIT: This how I have done and this is what my question is about. Perhaps there is a better way too do this?

for(int i=0;i<customerList.size();i++){
    System.out.println(customerList.get(i).getAccountOwnerName());
    System.out.println(customerList.get(i).getAccountOwnerPersonalNumber());
}

THIS IS MY OLD QUESTION: But know I have a problem and I have searched for a solution to iterate through an arraylist and get each value from the objects methods like getAccountOwnerName and getAccountNumber. I thought this code could be a start, but I need some help to develop it further or perhaps there is some better way to do this? Thanks!

System.out.print("List of customer");
Iterator<String> itr = customerList.iterator();

while (itr.hasNext()) {
    String element = itr.next();
    System.out.println(element + " ");
}

Upvotes: 0

Views: 99

Answers (2)

Gray
Gray

Reputation: 116848

All objects that implement Collection like ArrayList support the new for loop as of Java 1.5. Really anything that implements Iterable does. This means you can do something like:

for (Customer customer : customerList) {
   System.out.println(customer.getAccountOwnerName());
   System.out.println(customer.getAccountOwnerPersonalNumber());
}

This should be more efficient that doing repeated get(i). This uses the iterator method internally but is a lot easier to code to. Here's a good link of information:

http://blog.dreasgrech.com/2010/03/javas-iterators-and-iterables.html

You can also iterate through arrays although they don't implement Iterable:

Customer[] customers = new Customer[100];
customers[0] = new Customer();
...
for (Customer customer : customers) {
   System.out.println(customer.getAccountOwnerName());
   System.out.println(customer.getAccountOwnerPersonalNumber());
}

Upvotes: 3

Stijn Geukens
Stijn Geukens

Reputation: 15628

for (String s : customerList) {
    System.out.println(element + " ");
}

http://www.developer.com/java/other/article.php/3343771/Using-Foreach-Loops-in-J2SE-15.htm

Upvotes: 1

Related Questions