开发者

Error when typecasting in java

Hey guys, am trying to write to do type casting in java, but i keep getting

run: 
[(E,1), (H,1), (F,2), (G,2), (I,5), ( ,7)]
(H,1)
class datacompression.tuple
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to datacompression.tuple
    at datacompression.Chap3.huffman(Chap3.java:79)
    at datacompression.Chap3.histogram(Chap3.java:37)
    at datacompression.Main.main(Main.java:18)
Java Result: 1

this the source code:

import java.util.ArrayList;

/**
 *
 * @author Cubearth
 */
public class Chap3 {

    public static void huffman(ArrayList<tuple> list){
        //creates an huffman tree
        ArrayList<Node> huff = new ArrayList<Node>();
        for(int i = 0; i<list.size(); i++){
            huff.add(i, new Node(list.get(i), 2));
            huff.get(i).setScore(list.get(i).getB());
        }

        System.out.println(huff.get(1).getData().toString());
        System.out.println(huff.get(1).getData().getClass());
        while(huff.size()>1)开发者_JAVA百科{
            String msg = ((tuple)(huff.get(0).getData())).getA()+ ((tuple)(huff.get(1).getData())).getA();
            Node tmp = new Node(msg, 2);
            tmp.setChild(huff.get(0), 1);
            tmp.setChild(huff.get(1), 1);
            tmp.setScore((huff.get(0).getScore()+huff.get(1).getScore()));
            huff.set(0, tmp);
            huff.remove(1);
            sort2(huff);
        }
        System.out.println(huff);
        Tree tmp = new Tree(huff.get(0));
        tmp.print(2);
    }

    public static void sort2(ArrayList<Node> list){
            //sort an arrayList of node, uesing insertion sort
        int pos, min;
        for(pos = 0; pos<list.size()-1; pos++){
            min = pos;
            for(int i = pos+1; i<list.size(); i++){
                if(list.get(i).getScore()< list.get(pos).getScore())
                    min = i;
            }
            if(min!=pos){
                swap2(list, pos, min);
            }
        }
    }

    public static void swap2(ArrayList<Node> list, int a, int b){
            //swap two indexes of list
        Node bucket = new Node(list.get(a).getData(), list.get(a).getNoc());
        list.set(a, list.get(b));
        list.set(b, bucket);
    }
}

why my check for class in the huffman method comes up as a tuple(), but am unable to cast it as one?


well, initially huff.get(0).getData() might come as a 'tuple', but in this line:

huff.set(0, tmp);

you set it to be a String (as tmp is a String), so in the next iteration it will complain

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜