0

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.

Community
  • 1
  • 1
arsarc
  • 443
  • 1
  • 9
  • 22

4 Answers4

2

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());
}
Guillaume Barré
  • 4,168
  • 2
  • 27
  • 50
1
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

TheKojuEffect
  • 20,103
  • 19
  • 89
  • 125
1

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());
}
André Stannek
  • 7,773
  • 31
  • 52
1

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)
...
Andriy Kryvtsun
  • 3,220
  • 3
  • 27
  • 41