package com.company;
import java.util.Arrays;
public class GenericStack<E> {
E [] a = (E[]) new Object[1];//不可以new E[]
// int max = a.length;
int size = 0;
// E[] array = new [10]; 不可这么写
public int getSize() {
return size;
}
public E peek(){
return (E) a[size-1];
}
public void push(E o){
if(size==a.length){
E[]b = (E[])new Object[a.length*2];
// for(int i=0;i<a.length;i++)
// b[i]=a[i];
System.arraycopy(a,0,b,0,a.length);//原数组,第几位开始,目标数组,第几位,一共复制多少位;
a=b;
}
a[size++]=o;
}
public E pop(){
return (E) a[--size];
}
public boolean isEmpty(){
return size==0;
}
@Override
public String toString() {
return "GenericStack{" +
"a=" + Arrays.toString(a) +
", size=" + size +
'}';
}
public static void main(String[] args) {
GenericStack<String> s1 = new GenericStack<>();
s1.push("londno");
s1.push("londno2");
s1.push("londno3");
GenericStack<Integer> s2 = new GenericStack<>();
s2.push(1);
s2.push(2);
s2.push(3);
System.out.println(s1.pop()+" "+s1.pop());
System.out.println(""+s2.pop()+s2.pop()+s2.pop());
System.out.println(s1.isEmpty()+" "+s2.isEmpty());
}
}
java语言程序设计(进阶篇)19.1泛型的应用
最新推荐文章于 2022-11-14 12:48:11 发布