[JAVA] ArrayList 구현

CheolHyeon Park·2022년 7월 27일
0

Java

목록 보기
9/9

ArrayList와 Array 차이

  • Array는 초기값을 할당하여 고정되지만, ArrayList는 고정되지 않고 현재 size보다 늘어난다면 알아서 늘어난다.

구현

  • initial capacity만큼 차면 새로운 Array를 만든다.
  • 요소를 새로운 Array에 옮긴다.
    public boolean add(E e) {  
        ensureCapacityInternal(size + 1);  //  modCount!! increments  
        elementData[size++] = e;  
        return true;  
    }
      
    private void ensureCapacityInternal(int minCapacity) // Detemining the current size of occupied elements  
		{  
        	if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {  
 	           minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); // here, Math.max will  return the maximum or largest value from the given arguments DEFAULT_CAPACITY AND minCapacity  
        	}  
   
        	ensureExplicitCapacity(minCapacity);  
    	}  
      
    private void ensureExplicitCapacity(int minCapacity) {  
        modCount++; //modCount increases  
   
        // overflow-conscious code  
        if (minCapacity - elementData.length > 0)  
            grow(minCapacity);  
    }  
      
    private void grow(int minCapacity) // The grow method expands the size of the Array  
		{  
          // overflow-conscious code  
          int oldCapacity = elementData.length;  
          int newCapacity = oldCapacity + (oldCapacity >> 1);  
          if (newCapacity - minCapacity < 0)  
              newCapacity = minCapacity;  
          if (newCapacity - MAX_ARRAY_SIZE > 0)  
              newCapacity = hugeCapacity(minCapacity); //minCapacity will be close to the size of the array  
          elementData = Arrays.copyOf(elementData, newCapacity); // The Arrays.copyOf will copy the specified array  
	    }  

참고: https://www.javatpoint.com/arraylist-implementation-in-java

profile
나무아래에 앉아, 코딩하는 개발자가 되고 싶은 박철현 블로그입니다.

0개의 댓글