此代码用于学习泛型类和堆栈操作。 但它有一些关于声明变量类型
的错误package lab11_2_590510535;
import java.util.Scanner;
class Queue <TYPE>{
private int count;
private int front;
private int rear;
private int n;
private Object [] item;
private TYPE queueFront;
static void pl(Object a){System.out.println(a);}
static void p(Object a){System.out.print(a);}
Queue(int x){
n = x;
item = new Object[n];
front = 0;
rear = -1;
count = 0;
}
public boolean isEmpty(){
for(int i = 0 ; i<item.length ; i++){
if(item[i] != null){return false;}
}
return true;
}
public boolean isFull(){
if(item[item.length] != null){return true;}
else{return false;}
}
public void enqueue(TYPE v){
if(!isFull()){
if(rear < n-1){
rear++;
item[rear] = v;
count++;
}
}else{pl("Queue is Full.");}
}
public TYPE dequeue(){
if(!isEmpty()){
queueFront = item[front];
front++;
count++;
}else{p("Queue is empty.");}
return queueFront;
}
public void show(){
for(int i = 0 ; i <item.length ; i++){
if(item[i] != null){p(item[i] + ", ");}
}
}
public class Lab11_2_590510535 {
static void pl(Object a){System.out.println(a);}
static void p(Object a){System.out.print(a);}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner keyboard = new Scanner(System.in);
char choice;
int N;
p("Enter N: ");
N = keyboard.nextInt();
p("Choice input type; int(1) , char(2): ");
choice = keyboard.next().charAt(0);
if(choice == '1'){Queue <Integer> q = new Queue(N);}
else if(choice == '2'){Queue <Character> q = new Queue(N);}
do{
pl("1) enqueue"); pl("2) dequeue"); pl("3) show"); pl("4) exit");
p("Enter function number : ");
choice = keyboard.next().charAt(0);
if(choice == '1'){
p("Enter data: ");
Object s = keyboard.next();
q.enqueue(s);
}
else if(choice == '2'){Object s = q.dequeue();
pl(s);
}
else if(choice == '3'){q.show();}
}while(choice != '4');
}
}
1.用户输入选择后,我在do ... while循环中使用类型转换创建通用对象,但找不到“q”。
2.在public TYPE dequeue()方法行“queueFront = item [front];”对象无法转换为TYPE,我该如何修复它。
答案 0 :(得分:0)
尝试将private Object [] item
更改为private TYPE [] item
。您还需要知道如何为您的示例创建通用数组:
How to create a generic array?
How to create a generic array in Java?
您需要将item = new Object[n];
更改为item = (TYPE[]) new Object[n];
但是你应该避免创建泛型类型,而应该注入它们或使用工厂来创建它们。