Java优先级队列错误

时间:2012-12-08 05:54:34

标签: java priority-queue

public LightsOutBFS(){
    //readtext
    int[] arr = new int[25];
    int[] state = new int[25];
    int[] soln = new int[25];

    boolean check=true;
    PriorityQueue<Node> q = new PriorityQueue<Node>();

    //Reading the text file
    try{
        FileInputStream fstream = new FileInputStream("switches.txt");
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;
        int i = 0;

        //Read File Line By Line
        while ((strLine = br.readLine()) != null)   {
                //tokenize strline
                StringTokenizer st = new StringTokenizer(strLine, " \n"); 
                while(st.hasMoreTokens()) { 
                arr[i]=Integer.parseInt(st.nextToken());
                i++;
            }
        //Close the input stream
        }in.close();


    }catch (Exception e){//Catch exception if any
         System.err.println("Error: " + e.getMessage());
    }
    for(int i=0; i<25; i++){
        state[i]=0;
        soln[i]=0;
    }
    //loop that flips the adjacent side of switches turned on
    for(int i=0;i<25;i++){
        if(arr[i]==1)
            method.flip_adjacent(i,state);
    }


    //implement bfs here
    parent = new Node(state,0,soln,null);


    q.offer(parent);
    while(check){
        while(!q.isEmpty()){
            Node x = q.poll();
            int depth = x.depth;
            int posMoves = 25-depth;
            for(int i=0; i<posMoves;i++){
                current = generateNode(x.state,depth,x.soln,x);
                if(EtoNaYun(current.state))
                    check=false;//check state;
                q.offer(current);
            }
        }
    }

}

我正在尝试使用类优先级队列并将其类型化为节点对象,但我的代码显示了此异常:java.lang.ClassCastException:节点无法强制转换为java.lang.comparable。任何的想法?将优先级队列强制转换为对象是错误的吗?提前谢谢!

1 个答案:

答案 0 :(得分:1)

从错误消息中可以清楚地看出,您的程序失败了,因为您使用的Node类没有实现Comparable<T>接口。没有Comparable<T>接口PriorityQueue将不知道如何对元素(Node对象)进行排序。

<强>解决方案:

让你的Node类实现Comparable接口并覆盖public int compareTo(Obj o);根据一些id / priority来比较Node(我不知道Node类的定义,但可能是x.depth?)

public Node implements Comparable<Node> {
   ...
   @Override
   public int compareTo(Node o) {
    return this.priority > o.priority;
   }
}