欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

动态数组 博客分类: Java  

程序员文章站 2024-03-16 16:27:58
...

 

看tomcat源码中StandardService类的addConnector()中有个动态的为数组增加数据方法

@Override
    public void addConnector(Connector connector) {
        synchronized (connectors) {
            connector.setService(this);
            Connector results[] = new Connector[connectors.length + 1];
            System.arraycopy(connectors, 0, results, 0, connectors.length);
            results[connectors.length] = connector;
            connectors = results;
       }
}

 所以我也模仿它自己实现了一个

public class DynamicArray {
	protected String strs[] = new String[0];
	public void addString( String connector ) {
		String results[] = new String[strs.length + 1];
		System.arraycopy(strs, 0, results, 0, strs.length);
		results[strs.length] = connector;
		strs = results;
	}

	@Test
	public void test() {
		System.out.println(Arrays.toString(strs));
		addString("1");
		System.out.println(Arrays.toString(strs));
		addString("2");
		System.out.println(Arrays.toString(strs));
		addString("2");
		System.out.println(Arrays.toString(strs));
	}
}