在这里插入代码片
/*
* 1.泛型的方法自定义栈
* */
class MyStack<T>{
private T[] elements;
private int top;//栈顶指针相当于elements.length或size
private static final int defaultCapacity=5;//数组长度
public MyStack(){
this(defaultCapacity);
}
public MyStack(int capacity){
this.elements=(T[])new Object[capacity];
}
public boolean isEmpty(){
return top==0;
}
//入栈
public void push(T value){
//判满扩容
if(top==elements.length){
elements=Arrays.copyOf(elements,elements.length+(elements.length>>1));
}
elements[top++]=value;
}
//获取栈顶元素并删除
public T pop(){
//判空
if(isEmpty()){
throw new UnsupportedOperationException("the stack has been empty");
}
T result=elements[top-1];
elements[--top]=null;//方便垃圾回收,数组的元素并没有少,只是变成了null.
return result;
}
//获取栈顶元素不删除
public T peek(){
if(isEmpty()){
throw new UnsupportedOperationException("the stack has been empty");
}
return elements[top-1];
}
public String toString(){
//stack.elements 存放元素String 具有不变性
// String str="abc"
//String str="abc"+"d"+"e";
//一个+符号,底层实现一个StringBuilder对象,然后调用StringBuilder对象的append()方法进行字符串的追加
StringBuilder str1=new StringBuilder();
for(int i=0;i<top;i++){//返回有效元素,如果是elements.length就会有null
str1.append(elements[i]+" ");
}
return str1.toString();//任何一个对象想要以字符串的形式返回都得重写toString
}
//Jvm重写的
/* @Override
public String toString() {
return "MyStack{" +
"elements=" + Arrays.toString(elements) +
", top=" + top +
'}';
}*/
}
class Test4{
public static void main(String[] args) {
MyStack<Integer> stack=new MyStack<>();
stack.push(3);
stack.push(4);
stack.push(5);
stack.push(6);
stack.push(7);
stack.push(8);
System.out.println(stack);
System.out.println( stack.pop());
System.out.println(stack);
System.out.println(stack.peek());
System.out.println(stack);
}
}
//代码运行结果
3 4 5 6 7 8
8
3 4 5 6 7
7
3 4 5 6 7
Process finished with exit code 0
``
泛型方法自定义栈
最新推荐文章于 2021-06-11 13:00:18 发布