用数组实现支持泛型的栈,支持动态扩容
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;
}
}有考虑不周的地方欢迎指出
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;
}
}有考虑不周的地方欢迎指出
相关文章推荐
- JAVA泛型—— 3fe8 转
- JAVA泛型详解——转
- ruby 数组使用教程
- Ruby中的数组和散列表的使用详解
- C#实现AddRange为数组添加多个元素的方法
- C#动态调整数组大小的方法
- 详解Lua中的数组概念知识
- Perl中的列表和数组学习笔记
- 编写高质量代码改善C#程序――使用泛型集合代替非泛型集合(建议20)
- 探索PowerShell (八) 数组、哈希表(附:复制粘贴技巧)
- C#中数组初始化与数组元素复制的方法
- C#交错数组用法实例
- Linux Shell 数组建立及使用技巧
- PowerShell数组的一些操作技巧
- C#通过yield实现数组全排列的方法
- C#不重复输出一个数组中所有元素的方法
- C#实现将数组内元素打乱顺序的方法
- C#通过反射创建自定义泛型
- C#泛型用法实例分析
- Ruby简明教程之数组和Hash介绍