您的位置:首页 > 其它

用数组实现支持泛型的栈,支持动态扩容

2015-10-16 20:31 435 查看
       涉及到的知识点:

1.如何定义泛型类和泛型函数

2.如何抛出异常

3.如何定义支持泛型的数组

4.数组如何扩容,假设有int[] arrInt1=new Int[10]; 和int[] arrInt2=new int[20]; 可以直接arrInt1=arrInt2; 吗?

5.反射,动态建立泛型数组

关于泛型,推荐看下这篇博客。因为对于栈来说,如果在栈中没有元素时还调用pop()的话,应该抛出一个异常,如何定义一个抛出异常的函数?参看这篇博客。下面是具体实现:import java.lang.reflect.Array;

public class ArrStack<T> {

public static int CAPCITY = 10;//默认容量为10
public int depth = 0;//0表示栈为空
public T[] arr;//数组
Class<T> type;//接收类型信息

public ArrStack(Class<T> type) {
this(type, CAPCITY);
}

@SuppressWarnings("unchecked")
public ArrStack(Class<T> type, int cap) {
ArrStack.CAPCITY = cap;
this.type = type;
arr = (T[]) Array.newInstance(type, cap);
}

public void push(T value) {
if (depth + 1 == CAPCITY) {//栈满则扩容,容量为原来的两倍
@SuppressWarnings("unchecked")
T[] tempArr = (T[]) Array.newInstance(type, 2 * CAPCITY);
CAPCITY = 2 * CAPCITY;
for (int i = 0; i < arr.length; i++)
tempArr[i] = arr[i];
arr = tempArr;
}
arr[++depth] = value;
}

public T pop() throws Exception {// 此处最好不用抛出异常,这是由程序逻辑引起的,在pop的时候判断depth即可避免
if (depth > 0)
return arr[depth--];
throw new Exception("空栈");
}

public int getSize() {//返回当前栈深
return depth;
}
}有考虑不周的地方欢迎指出
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数组 泛型