Java开关/案例与问题

和杰伊

我一直在尝试使用java类来模拟Stack这是我的类构造函数:

        public Stack(Class<?> type){

        if(type==String.class){

                //...

            }

            switch(type){

                    case (String.class):
                            //...
                    break;
                    case (Integer.class):
                            //...
                    break;

                    case (Double.class):
                            //...
                    break;

                    case (Byte.class):
                            //...
                    break;

                    default:
                    break;

            }

            this.counter = -1;

        }

但令我困惑的是,if块可以正常工作。但是使用switch / case块无法编译。

错误说

incompatible types
                switch(type){
                       ^
  required: int
  found:    Class

error: constant expression required
case (String.class):

在开关块中的所有情况下都将重复此操作。

请在这里指出我是否遗漏任何东西。

路易吉·门多萨(Luiggi Mendoza)

代码中的主要问题switch语句的错误使用这将仅适用于工作不变(文字或final从原始类型标记变量)byteshortcharint由于Java 5,它也允许这些原语的相应包装类的常量变量:ByteShortCharacterInteger,并且还支持enumS,并且由于Java 7的支持恒定String变量。Java教程对此进行了介绍switch语句因此,要修复您当前的代码,请使用if语句代替switch

//when comparing object references, use the equals method, not ==
if (String.class.equals(type)) {
    //...
} else if (Integer.class.equals(type)) {
    //...
} else ...

根据您的评论:

只是需要为Stack构建一个类设计,该设计可以使用许多数据类型。我做了什么坏事吗?

设计中的主要问题是,您必须在此长长的if列表中基本上添加任何Java类和自定义类,这甚至会使您的代码变得非常丑陋,糟糕甚至是一场噩梦为了解决这个问题,Java从Java 5开始就为我们提供了泛型。因此,您可以这样定义类:

class MyStack<E> {
    //implementing the stack using a generic single linked list
    class Item {
        E data;
        Item next;
    }
    private Item head;
    private Item tail;
    private int size = 0;
    public MyStack() {
    }
    public int getSize() {
        return this.size;
    }
    public void add(E e) {
        Item temp = new Item();
        temp.data = e;
        if (head == null) {
            head = temp;
        } else {
            tail.next = temp;
        }
        tail = temp;
        size++;
    }
    //add the rest of the behavior...
}

顺便说一句,StackJava Collections API中已经有一个类,并且您不应具有与Java JDK API相同名称的任何类。这就是为什么在我的示例中,调用stack类的原因MyStack

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章