黑马集合学习 自定义ArrayList01

 1 package demo;
 2 
 3 import java.util.Arrays;
 4 
 5 public class MyArrayList<T> {
 6     Object[] t;
 7     int size;
 8     private static final int MAX_ARRAY_SIZE = 5;
 9     private static final Object[] EMPTY_ELEMENTDATA = {};
10 
11     public MyArrayList(){
12         //必须给t赋值,不然每次都必须判断t是否为null,影响效率
13         t = EMPTY_ELEMENTDATA;
14     }
15 
16     public boolean add(T e){
17         //必须给t赋值,不然每次都必须在这里判断t是否为null,影响效率
18         if(t.length == size){
19             grow(size + 1);
20         }
21         t[size++] = e;
22         return true;
23     }
24 
25     private void grow(int minCapacity) {
26         int newCapacity = t.length + t.length >> 1;
27         //minCapacity溢出
28         if(minCapacity < 0)
29             throw new RuntimeException();
30         //newCapacity < minCapacity必须加,因为刚开始时newCapacity增长小于minCapacity
31         if(newCapacity < minCapacity || newCapacity < 0 || newCapacity > MAX_ARRAY_SIZE){
32             if(minCapacity > MAX_ARRAY_SIZE){
33                 throw new RuntimeException();
34             }else{
35                 //生长到最大
36                 t = Arrays.copyOf(t, MAX_ARRAY_SIZE);
37             }
38         }else{
39             //生长到newCapacity
40             t = Arrays.copyOf(t, newCapacity);
41         }
42     }
43 }
ArrayList一
原文地址:https://www.cnblogs.com/mozq/p/10732711.html