java - How should i resolve this ClassCastException? -


getting classcastexception when adding vertex linked list when doing bfs. need information: vertex user defined class has linked list of edge class objects.

here code:

private void reachable() {         clearall();          (vertex v : vertexmap.values())             v.setcolor("white");          (vertex s : vertexmap.values())             if (s.isstatus())                 bfs(s);     }      private void bfs(vertex s) {          s.setcolor("gray");         s.dist = 0;         s.prev = null;          queue<vertex> vertices = new priorityqueue<vertex>();         vertices.add(s);          while (!vertices.isempty()) {             vertex u = vertices.remove();             (iterator = u.adjacent.iterator(); i.hasnext();) {                 edge edge = (edge) i.next();                 vertex adj = edge.getdestvertex();                 if (!adj.getname().equals(u.getname()) && adj.isstatus())                     if (adj.getcolor().equals("white")) {                         adj.setcolor("gray");                         adj.dist = u.dist + 1;                         adj.prev = u;                         vertices.add(adj);                     }             }             u.setcolor("black");         }     } 

i'm guessing problem here:

    queue<vertex> vertices = new priorityqueue<vertex>();     vertices.add(s);  // <<<---- here 

a priorityqueue needs able compare instances of parameter type (i.e. vertex) determine relative priority. if instantiate queue comparator<vertex> object parameter, queue use determine priority. otherwise, expects vertex implement comparable<vertex>.

the exception occurring because inside add operation, code trying cast vertex objects comparable.

solutions:

  1. declare class ... class vertex implements comparable<vertex> , provide implementation of int compareto(vertex) method.

  2. implement comparator<vertex> class implementation of int compare(vertex, vertex) , pass instance priorityqueue constructor. (you use anonymous class.)

either way, compare / compareto method basis queue's prioritization. implement accordingly.


Comments

Popular posts from this blog

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -