这是我用于堆栈/队列分配的主要方法。我的队列一直有错误,但我的 Stack 没有。堆栈类似乎工作得很好。我完全卡住了。它说“无法实例化类型队列”。非常感激任何的帮助!
public class mainMeth {
public static void main(String[] args) throws FileNotFoundException {
File Polish = new File("fILE4INPUT.txt");
File out = new File("outfile.txt");
Scanner f = new Scanner(Polish);
Queue inputQ = new Queue();
Stack stack2 = new Stack();
Queue outputQ = new Queue();
String word;
Character ch;
while (f.hasNext()) {
String myString = f.nextLine();
for (int count = 0; count < myString.length(); count++) {
ch = myString.charAt(count);
inputQ.addtoRear(ch);
}
while (!inputQ.ismtQ()) {
ch = inputQ.remfront();
if (isAlpha(ch)) {
// System.out.println(ch);
outputQ.addtoRear(ch);
} else {
if (isOperator(ch)) {
if (stack2.ismt()) {
stack2.push(ch);
} else {
if (valueOf(ch) > valueOf(stack2.top())) {
stack2.push(ch);
} else {
outputQ.addtoRear(stack2.pop());
stack2.push(ch);
}
}
}
}
}
while (!stack2.ismt()) {
outputQ.addtoRear(stack2.pop());
}
System.out.println(outputQ.toString() + "\n\n");
while (!outputQ.ismtQ()) {
outputQ.remfront();
}
}
}
public static boolean isAlpha(Character ch) {
boolean retVal = false;
if (ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z')
retVal = true;
return (retVal);
}
public static boolean isOperator(Character ch) {
boolean retVal = false;
if (ch == '+' || ch == '-' || ch == '/' || ch == '*')
retVal = true;
return (retVal);
}
public static int valueOf(Character ch) {
int retval = 0;
if (ch == '/' || ch == '*')
retval = 2;
else
retval = 1;
return retval;
}
}
最佳答案
在Interfaces Java 文档部分:
Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces.
那么你不能直接实例化 interface Queue<E>
.但是,您仍然可以引用实现 Queue
的对象。按接口(interface)类型的接口(interface),例如:
// As I saw that you are adding Characters to your queue
Queue<Character> inputQ = new PriorityQueue<Character>();
您可以根据您的要求选择适当的实现,这里是所有具体和已知实现类的列表,来自 java docs :
ArrayBlockingQueue
,ArrayDeque
,ConcurrentLinkedDeque
,ConcurrentLinkedQueue
,DelayQueue
,LinkedBlockingDeque
,LinkedBlockingQueue
,LinkedList
,LinkedTransferQueue
,PriorityBlockingQueue
,PriorityQueue
,SynchronousQueue
关于java - 无法实例化 Queue 类型。为什么是这样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28641605/