自定义ArryList

自定义ArrayList

自定义ArryList_第1张图片

这个自定义的ArrayList是用来熟悉ArryList,体会ArryList的底层原理。

package cn.xiaomu_mycollection;
/**
 * 
 * @author 小沐
 *
 */
public class SetArryList {
	private Object[] elementData;  // 数组
	private int size;              // 长度
	private static final int DEFALT_CAPACITY=10;    //默认数组长度
	
	public  SetArryList() {
		elementData = new Object[DEFALT_CAPACITY]; 
	}
	
	public SetArryList (int capacity) {
		elementData = new Object[capacity]; 
	}
	
	public void add(E object) {
		elementData[size++] = object;
	}
	
	@Override
	public String toString() {  // 重写toString方法
		// TODO Auto-generated method stub
		StringBuilder sBuilder = new StringBuilder();
		//a,b,c
		sBuilder.append("[");
		 for (Object object : elementData) { 
			/*  如果不想打出空值,即可启用该循环
			 * for (int i = 0; i < size; i++) { sBuilder.append(elementData[i]+","); } 
			 */
			sBuilder.append(object+",");
		}
		sBuilder.append("]");
		
		return sBuilder.toString();
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		SetArryList s1 = new SetArryList(20);
		s1.add("abc");
		s1.add("数组");
		
		System.out.println(s1);
	}

}

 

你可能感兴趣的:(JAVA)