注:
以下代码不涉及算法和数据结构,是直接使用java里面的方法来实现的。可以熟悉一下ArrayList的用法。
public class MyStack{
public static void main(String[] args) {
MyStack stack = new MyStack();
stack.list.add(4);
stack.list.add(5);
stack.list.add(6);
stack.list.add(7);
stack.list.add(8);
stack.list.add(9);
System.out.println("Is stack empty ? "+stack.isEmpty());
Object o= new Object();
o=100;
System.out.println("the peek is "+stack.peek());
System.out.println("the size is "+stack.getSize());
stack.pop();
System.out.println("after pop, the new size is "+stack.getSize());
System.out.print("after push a new object " );
stack.push(o);
System.out.println(",the position of the new object is "+stack.search(o));
System.out.println("show all of number from top to bottom :\n");
for(int i = (stack.getSize()-1);i>=0;i--)
System.out.print(stack.list.get(i)+" ");
}
static java.util.ArrayList list= new java.util.ArrayList();
public boolean isEmpty() {
return list.isEmpty();
}
public int getSize() {
return list.size();
}
public Object peek() {
return list.get(getSize()-1);
}
public Object pop() {
Object o= new Object();
list.remove(getSize()-1);
return o;
}
public void push (Object o) {
list.add(o);
}
public int search(Object o) {
return list.lastIndexOf(o);
}
public String toString() {
return "Stack"+list.toString();
}
}
感觉自己写java的习惯一点都不好,昨天才了解到继承和多态,结果我所有的源代码都放在一个默认的包里了,自己不去建包,而且去封装类的时候做得也不好,总喜欢一块代码写完,把test和类和在一起写看起来就不太规范。还有就是现在还不太懂类之间的调用操作,写出来经常报错,虽然找一小会就能改过来,但是…就是没掌握好。