开发者

why it throws java.lang.classCastException

this is my class and I want to sort my stack but it will throw an exception please help me thanks!

public class jj {
    public static void main(String[] args){
        Stack<Integer> s = new ImplimentingAStackUsingAnArrayOfAGivenSizeN(5);
        s.push(1);
        s.push(3);
        s.push(5);
        s.push(2);
        s.push(4);
        Collections.sort((List<Integer>) (s));
        System.out.println(s);
        while (!s.isEmpty()) {
            System.out.println(s.pop());
        }
    }
}

the stack traces:

Exception in thread "main" java.lang.ClassCastException: 
datastructurechapter5.ImplimentingAStackUsingAnArrayOfAGivenSizeN 
cannot be cast to java.util.List at datastructurechapter5.jj.main(jj.java:24)  
   `Collections.sort((List<Integer>) (s));`
Java Result: 1
BUILD SUCCESSFUL (total time: 2 secon开发者_Go百科ds)


I'd assume you are using (and extending) a wrong Stack. Make sure you have

import java.util.Stack;

If the Stack is some class of yours, you'd have to define it to impelement List:

public class Stack implements List {..}

But that would be a lot of work, so use java.util.Stack

Note: As Jesper commented, you'd better use java.util.Deque (perhaps ArrayDeque)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜