标签:style blog io ar color sp java on div
1 package StudyCollection; 2 3 import java.util.Collections; 4 5 /** 6 * 底层实现简单容器 7 * 8 * @author ouyang-an 谢谢尚学堂 高琪 老师 9 */ 10 11 public class MakeArray { 12 private Object[] elementData; 13 private int size; 14 15 public MakeArray() { // 无参构造器 16 this(10); 17 } 18 19 public MakeArray(int initialCapacity) { // 带参构造器 20 if (initialCapacity < 0) { 21 try { 22 throw new Exception(); 23 } catch (Exception e) { 24 e.printStackTrace(); 25 } 26 27 } 28 elementData = new Object[initialCapacity]; 29 } 30 31 public void add(Object obj) { // add()方法 32 if (size == elementData.length) { 33 Object[] newArray = new Object[size * 2]; 34 System.arraycopy(elementData, 0, newArray, 0, 35 elementData.length); 36 elementData = newArray; 37 } 38 elementData[size] = obj; 39 size++; 40 } 41 42 // size方法 43 public int size() { 44 return size; 45 } 46 47 // 判断数组是否为空 48 public boolean isEmpty() { 49 return size == 0; 50 } 51 //get方法 52 public Object get(int index) { 53 if (index < 0 || index >= size) { 54 try { 55 throw new Exception(); 56 } catch (Exception e) { 57 e.printStackTrace(); 58 } 59 } 60 return elementData[index]; 61 } 62 //set方法 63 public Object set(int index) { 64 return elementData[index]; 65 } 66 public static void main(String[] args) { 67 MakeArray list = new MakeArray(); 68 list.add("a"); 69 list.add("123"); 70 list.add("sadf"); 71 list.add("dsafas"); 72 System.out.println(list.size); 73 System.out.println(list.isEmpty()); 74 System.out.println(list.get(3)); 75 } 76 }
标签:style blog io ar color sp java on div
原文地址:http://www.cnblogs.com/Ouyangan/p/4119507.html