当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Iterating a collection of Javabeans as an arraylist?

问题描述:

Originally I have been using arraylists like this:

ArrayList<JavaBean> AllBeans = new ArrayList<JavaBean>();

And I'm able to iterate through it and get it to print all of my beans like this:

for (int i=0;i<AllBeans.size();i++){

System.out.println(AllBeans.get(i).getCost());

}

But I found out I should be doing this:

Collection<JavaBean> AllBeans = new ArrayList<JavaBean>();

But if I do that, I no longer can do AllBeans.get(i).getCost(), so I read on stackoverflow, and I apparently need to user an iterator. But, I don't understand what I'm doing. I want to be able to use the original bean classes, but I can't get to them? I just want to use my bean.getCost() from my bean object.

The only thing I could get was

Iterator itr = new AllBeans.Iterator();

while (itr.hasNext()){

System.out.println(itr.next().toString())

}

Which doesn't get to my object at all? I'm still having trouble understanding abstract and interface in java.

网友答案:

Using an iterator you can get your object

Collection<JavaBean> AllBeans = new ArrayList<JavaBean>();
Iterator<JavaBean> itr = AllBeans.iterator();
while (itr.hasNext()) {
    System.out.println(itr.next().getCost());
}

If you use just Iterator itr instead of Iterator<JavaBean> itr then you need to cast the object returned by itr.next();

Iterator it = AllBeans.iterator();
while (it.hasNext()) {
    JavaBean bean = (JavaBean)it.next();
    System.out.println(bean.getCost());
}
网友答案:
Collection<JavaBean> AllBeans = new ArrayList<JavaBean>();
AllBeans.get(i).getCost();

It was not working because AllBeans is a variable of type Collection which doesn't have get method. You can use

List<JavaBean> AllBeans = new ArrayList<JavaBean>();
AllBeans.get(i).getCost();

References:

java.util.Collection:https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html

网友答案:

You need to do this because Collection has no index while List has. Iterator is also generic so you can use it like this:

Iterator<JavaBean>  itr = AllBeans.iterator();
while (itr.hasNext()){
    System.out.println(itr.next().getCost());
}

The easier way is to use the enhanced for loop (aka for-each loop)

for (JavaBean bean : AllBeans){
    System.out.println(bean.getCost());
}
网友答案:

Use foreach Java statement

List<JavaBean> allBeans = new ArrayList<JavaBean>();
...
for (JavaBean bean: allBeans) {
   System.out.println(bean.getCost());
}

Also use Java identification convention: don't use uppercase for the first identification char. Use CamelCase convention.

If you use Java 8 the statement may be even simpler and flexible

...
allBeans.stream()
    .map(bean -> bean.getCost())
    .forEach(System.out::println)
...
分享给朋友:
您可能感兴趣的文章:
随机阅读: