-1
package example;

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

public class anaBolum {
    public static void main(String[] args) {
        ArrayList<IMeyveler> list = new ArrayList<>();
        list.add(new Muz());
        list.add(new Elma());

        Iterator it = list.iterator();
        while(it.hasNext()){
            it.next().fiyat() //compile error
        }
    }
}

I was use list.iterator() to access the list elements. But I can't access this method fiyat() in the iterator because I get compile error.

4
  • What is the error you are getting? Commented Dec 30, 2012 at 13:27
  • Too much of this question is in some local language. Try to internationalize it translating to English the names of methods and variables. Commented Dec 30, 2012 at 13:29
  • try the following: stackoverflow.com/questions/6700717/… Commented Dec 30, 2012 at 13:30
  • Also you should have precised that both Muz() and Elma() objects have the fiyat() method. Commented May 26, 2015 at 0:25

4 Answers 4

0

I assume you are getting some compile time error. If so You need to change the iterator declaration to Iterator<IMeyveler> it = list.iterator();

Other wise the iterator will not know the type of objects handled by it.

public class anaBolum {
    public static void main(String[] args) {
        IMeyveler muz = new Muz();
        muz.fiyat();// Work

        ArrayList<IMeyveler> list = new ArrayList<>();
        list.add(new Muz());
        list.add(new Elma());

        Iterator<IMeyveler> it = list.iterator();
        while(it.hasNext()){
            System.out.println(it.next().fiyat());
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You need to do like this

    while(it.hasNext()){
        Object obj = it.next() ;
        if( obj instanceof Muz ) {
          Muz muz = (Muz) obj ;
          muz.fiyat();
        }
    } 

Comments

0

Your CodeCompletion does not show up, because .next() returns an object and not IMeyveler. You will either have to cast, or iterate differently.

    System.out.println(((IMeyveler)it.next()).fiyat());

Comments

0

Try this one:

package javaaa;

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

public class anaBolum {
    public static void main(String[] args) {
        IMeyveler muz = new Muz();
        muz.fiyat();// Work

        ArrayList<IMeyveler> list = new ArrayList<>();
        list.add(new Muz());
        list.add(new Elma());

        for(IMeyveler fruit : list)
        {
            if(fruit instanceof Muz)
            {
                System.out.println(fruit.fiyat());
            }
        }  
    }
}

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.