简体   繁体   中英

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 + " ");
}

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());
}
for (String s : customerList) {
    System.out.println(element + " ");
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM