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:
declare class
... class vertex implements comparable<vertex>, provide implementation ofint compareto(vertex)method.implement
comparator<vertex>class implementation ofint compare(vertex, vertex), pass instancepriorityqueueconstructor. (you use anonymous class.)
either way, compare / compareto method basis queue's prioritization. implement accordingly.
Comments
Post a Comment