简体   繁体   English

列出对象数组列表中的对象方法的值?

[英]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. 我正在学习Java编程,现在我正在探索arralist中对象的使用。 I know how to get a single value out of a object that are in a arraylist like this: 我知道如何从像这样的arraylist中的对象中获取单个值:

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. 这是我的老问题:但是知道我有一个问题,我已经在寻找一种解决方案,以遍历arraylist并从诸如getAccountOwnerName和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. 从Java 1.5开始,所有实现Collection对象(例如ArrayList支持新的for循环。 Really anything that implements Iterable does. 实际上,任何实现Iterable东西都可以做到。 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) . 这比重复执行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 http://blog.dreasgrech.com/2010/03/javas-iterators-and-iterables.html

You can also iterate through arrays although they don't implement Iterable : 您也可以遍历数组,尽管它们没有实现Iterable

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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