1 package StudyCollection; 2 3 /** 4 * 底层实现简单容器 5 * 6 * @author ouyang-an 谢谢尚学堂 高琪 老师 7 */ 8 9 public class MakeArray { 10 private Object[] elementData; 11 private int size; 12 13 // 无参构造器 14 public MakeArray() { 15 this(10); //这里默认大小是10 16 } 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 elementData = new Object[initialCapacity]; 28 } 29 30 // add()方法 31 public void add(Object obj) { 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 52 // 遍历 53 public void iteratesMethod() { 54 for (int i = 0; i < size; i++) { 55 Object array_element = elementData[i]; 56 System.out.println(i + ": " + array_element); 57 } 58 } 59 60 // get方法 61 public Object get(int index) { 62 if (index >= size) { 63 try { 64 throw new Exception(); 65 } catch (Exception e) { 66 e.printStackTrace(); 67 } 68 } 69 return elementData[index]; 70 } 71 72 // set方法 73 public Object set(int index, Object nObject) { 74 return elementData[index] = nObject; 75 } 76 77 public static void main(String[] args) { 78 MakeArray list = new MakeArray(); 79 list.add("11"); 80 list.add("22"); 81 list.add("33"); 82 list.add("44"); 83 list.iteratesMethod(); 84 System.out.println("------------------------"); 85 System.out.println(list.size); 86 System.out.println("------------------------"); 87 System.out.println(list.isEmpty()); 88 System.out.println("------------------------"); 89 System.out.println(list.get(3)); 90 System.out.println("------------------------"); 91 System.out.println(list.set(2, "ouyangan")); 92 System.out.println("------------------------"); 93 list.iteratesMethod(); 94 } 95 }