Java 基于栈的动态数组
Java 基于栈的动态数组
实现数组动态方式有:
Array.newInstance(…);
Arrays.copyOf(…);
例子使用Arrays.copyOf()方法的方式。
动态数组
package com.example;
import sun.security.util.Length;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
class MyStack<E> {
private int id;
private Object[] data={};//{} {}.length=0
public boolean push(E tmp){
synchronized (this){
if(data.length==id){
data=Arrays.copyOf(data, data.length+1);
}
data[id++]=tmp;
return true;
}
}
@SuppressWarnings("unchecked")
public E pop(){
synchronized (this){
if(id>0){
E e=(E) data[--id];
data=Arrays.copyOf(data, data.length-1);
return e;
}
return null;
}
}
@Override
public String toString() {
return Arrays.toString(data);
}
}
public class Test {
public static void main(String args[]) throws ClassNotFoundException, InterruptedException {
MyStack stack=new MyStack();
Thread th1=new Thread(new Runnable() {
@Override
public void run() {
stack.push(1);
stack.push("aa");
stack.push("bb");
}
});
Thread th2=new Thread(new Runnable() {
@Override
public void run() {
stack.push("bb");
stack.push("cc");
stack.pop();
}
});
th1.start();
th2.start();
th1.join();
th2.join();
System.out.println(stack.toString());
}
}