1
package test_run;

import java.util.ArrayList;
import java.util.Iterator;

class Al_class
{
  int x;

  Al_class() {
    x=0;
  }

  void increment(){
      ++x;
  }

  int get_value(){
      return x;
  }

    ArrayList<Al_class> class_declare(){
    //void class_declare(){
      Al_class alc1 = new Al_class();
      Al_class alc2 = new Al_class();
      Al_class alc3 = new Al_class();
      alc1.increment();
      alc1.increment();
      alc1.increment();
      alc2.increment();

      ArrayList al = new ArrayList();
      al.add(alc1);
      al.add(alc2);
      al.add(alc3);
      return al;
  }



} ///:~

class Main
{

  public static void main(String[] args) {
    Al_class a = new Al_class();
    ArrayList<Al_class> b;

    b=a.class_declare();
    a.class_declare();
    System.out.print(" Arraylist size= "+ b.size());

    for (Al_class c : b ){

        System.out.print("\n" + c.get_value() + "\n");
    }
    b.remove(0);
    System.out.print(" Arraylist size= "+ b.size());

    Iterator it= b.iterator();
    while (it.hasNext()) {
        System.out.print("\n" + it.next());
        // Al_class e=it.next();
        // System.out.print("\n" + e.get_value());          
    }
  }
}

How can I use iterator to call the object function get_value? Its not a homework, but self learning.

1
  • Why did you comment out the correct answer (in the while (it.hasNext()) method). Commented Jun 1, 2011 at 13:42

2 Answers 2

2

You must use generics, which means to change Iterator to Iterator<A1_class>:

Iterator<A1_class> it= b.iterator();
while (it.hasNext()) {
    Al_class e=it.next();
    System.out.print("\n" + e);
    System.out.print("\n" + e.get_value());          
}
Sign up to request clarification or add additional context in comments.

2 Comments

you are calling it.next() twice so, A1_class e will return a every 2nd element from the iterator and print the odd items in sysout.
@TheElite: thanks for notifying me, I simply uncommented the code from the sample ;-) Oh, the dangers of copy-and-paste!
0

You can approach a few ways

Explicit Cast

while (it.hasNext()) {
    Object o = it.next();
    if(o instanceof Al_class){
        Al_class e=(Al_class)o;
        System.out.print("\n" + e.get_value());  
    } 
} 

Generics

Iterator<A1_class> it= b.iterator();
while (it.hasNext()) {
    Al_class e=it.next();
    System.out.print("\n" + e.get_value());          
}

Your not really supposed to do explicit casting w/ type checking anymore, but its still in there and has limited use cases.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.