Home > Software design >  is it possible to change iterator type ? of iterator created from classes that implemets interface
is it possible to change iterator type ? of iterator created from classes that implemets interface

Time:12-04

is it possible to cast like this ?

Iterator<Class that implemets the interface> -->  Iterator<Interface>

i have this member in my Algo Class

 public HashMap<Integer, HashMap<NodeC, EdgeC>> edges;

on this function i am generating an iterator type <EdgeData> is need to return but the problem is that i am working with classes spesipclly with Edge Class so it throw an error

    @Override
    public Iterator<EdgeData> edgeIter(int node_id) {
 
       
            return this.edges.get(node_id).values().iterator();
        
      
    }


Incompatible types. Found: 'java.util.Iterator<src.api.Edge>', required: 'java.util.Iterator<src.interfaces.EdgeData>'```

program about graphs

structure

interfaces
  |-->  EdgeData
  |-->  Algo    

Classes 
  |--> Edge implements EdgeData
  |--> AlgoClass implements Algo

in my AlgoClass i am using a HashMap<Integer, HashMap<Node,Edge>> edges;

so that i get an edge in o(1) by first passing the source of the edge and then every Node has a hashmap inside of it of the destenations , so by passing the destenation i will get the correct Edge ! in o(1) approximitly .

problem is with the return type of the Iterator in edgeIter function , i need it to be EdgeData type like the interface EdgeData. and i dont know if it is possible to cast the Iterator to Iterator.

CodePudding user response:

Just change the return type to Iterator<? extends EdgeData>.

If you can't change that interface, you have to work around the bug (because that signature is just plain wrong). You can, with uglycasting. It'll generate warnings that you have to then suppress. Just cast to Iterator<EdgeData>.

  • Related