Stack<template> 称为类的泛型。也就是说指定了stack类中的数据为统一数据。比如将所有整数,或者字符类数据压入栈。如果出现将一个字符类的数据压入一个数据类的stack,系统则会报错。;比如下面的程序。Ops是一个string 类型的stack,vals是一个整数类型的stack。但是在ops中压入整数,在vals压入字符串,则会报错
public class study{
public static void main(String[] args) {
// TODO Auto-generated method stub
// Circle c = new Circle(47);
Stack<String> ops=new Stack<String>();
Stack<Integer> vals=new Stack<Integer>();
ops.push(1);
vals.push("test1");
}
}
提示如下错误:
Themethod push(String) in the type Stack<String> is not applicable for thearguments (int)
The method push(Integer) in the typeStack<Integer> is not applicable for the arguments (String)
改成如下形式则正确
public class study{
public static void main(String[] args) {
// TODO Auto-generated method stub
// Circle c = new Circle(47);
Stack<String> ops=new Stack<String>();
Stack<Integer> vals=new Stack<Integer>();
ops.push("test");
ops.push("test1");
vals.push(2);
vals.push(1);
for(String t:ops){
System.out.println("The string is:" + t);
}
}
}
也可以用类创建一个固定类长度的stack。如下自定义一个类,并用数组来模拟stack
classFixedCapacityStackofStrings{
private String a[];
private int n;
public FixedCapacityStackofStrings(int cap){
a=new String[cap];
}
public boolean isEmpty(){
return n==0;
}
public int size(){
return n;
}
public void push(String item){
a[n++]=item;
}
public String pop(){
return a[--n];
}
}
public class study{
public static void main(String[] args) {
// TODO Auto-generated method stub
// Circle c = new Circle(47);
FixedCapacityStackofStrings s=new FixedCapacityStackofStrings(100);
Scanner input=new Scanner(System.in);
while (true){
String item=input.next();
if (item.equals("quit")){
break;
}
if (!item.equals("-")){
s.push(item);
}
else if(!s.isEmpty()){
System.out.println(s.pop());
}
}
System.out.println(s.size());
System.out.println(s.pop());
}
}
FixedCapacityStackofStrings这个类只能处理String的数据,如果要处理double或者int的数据,则必须另外写一个类。这样的话就显得很冗余。可以创建泛型类来解决这个问题。
classFixedCapacityStack<Item>{
private Item a[];
private int n;
public FixedCapacityStack(int cap){
a=(Item[])new Object[cap];
}
public boolean isEmpty(){
return n==0;
}
public int size(){
return n;
}
public void push(Item item){
a[n++]=item;
}
public Item pop(){
return a[--n];
}
}
public class study{
public static void main(String[] args) {
// TODO Auto-generated method stub
// Circle c = new Circle(47);
FixedCapacityStack s=newFixedCapacityStack<Integer>(100);
Scanner input=new Scanner(System.in);
while (true){
String item=input.next();
if (item.equals("quit")){
break;
}
if (!item.equals("-")){
s.push(item);
}
else if(!s.isEmpty()){
System.out.println(s.pop());
}
}
System.out.println(s.size());
System.out.println(s.pop());
}
}