-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.

kibar
  • 822
  • 3
  • 17
  • 37

4 Answers4

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());
        }
    }
}
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

You need to do like this

    while(it.hasNext()){
        Object obj = it.next() ;
        if( obj instanceof Muz ) {
          Muz muz = (Muz) obj ;
          muz.fiyat();
        }
    } 
vels4j
  • 11,208
  • 5
  • 38
  • 63
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());
cppanda
  • 1,235
  • 1
  • 15
  • 29
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());
            }
        }  
    }
}
vtokmak
  • 1,496
  • 6
  • 35
  • 66