• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    미해결

ArrayList 질문

20.05.20 13:37 작성 조회수 533

0

ArrayList에는 용량이 정해져있지 않나요??

push 메소드를 이용해서 임의로 정한 용량보다 배열의 길이가 커지면 용량을 2배로 늘리는 기능을 구현하고 싶은데

임의로 정한 용량이 진짜 용량을 의미하는지 아니면 단지 변수일뿐인지 궁금합니다..

그리고 printStack 메소드를 호출하면 print는 되지만 다음과 같은 오류가 뜹니다.. 왜그런지 알수있을까요?ㅜ

list : 1 Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 1 out of bounds for length 1

at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)

at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)

at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)

at java.base/java.util.Objects.checkIndex(Objects.java:373)

at java.base/java.util.ArrayList.get(ArrayList.java:425)

at ParaStackAL.printStack(ParaStackAL.java:40)

at TestStack.main(TestStack.java:66)

-----------------------------------------------

코드입니다.

import java.util.ArrayList;

public class ParaStackAL<T> {

private ArrayList<T> list;

int capacity;

public ParaStackAL(int capacity) {

this.capacity = capacity;

setList(new ArrayList<T>());

}

public void push(T data) {

if(capacity <= getList().size()) {

System.out.printf("Increase Capacity : %d -> ", capacity);

capacity = capacity * 2;

System.out.println(capacity);

}

getList().add(data);

System.out.println("Inserted data : " + data);

}

public T pop() {

T temp = getList().get(getList().size() - 1);

getList().remove(getList().size() - 1);

System.out.println("Deleted data : " + temp);

return temp;

}

public boolean isEmpty() {

return getList().isEmpty();

}

public void printStack() {

        if(isEmpty()) {

            System.out.println("Stack is empty!");

        } else {

        System.out.print("list : ");

        for(int i=0; i<=list.size(); i++) {

                System.out.print(list.get(i) + " ");

            }

        }

            System.out.println();

    }

public ArrayList<T> getList() {

return list;

}

public void setList(ArrayList<T> list) {

this.list = list;

}

}

 

답변 3

·

답변을 작성해보세요.

1

구글링("java ArrayList capacity") 해보시면, 아래 메소드와 관련된 예제 또는 API 문서를 확인할 수 있겠습니다.

ensureCapacity(int minCapacity) 

0

모징님의 프로필

모징

질문자

2020.05.20

2배로 늘리는 기능은 어떤 메소드로 할 수 있나요??

0

배열은 크기가 고정되어있으나, ArrayList는 크기가 유동적입니다. 스스로 2배로 늘리거나, 반으로 줄이는 기능이 이미 구현되어있습니다.

질문하신 내용은 "자료구조"에서 배우게 되실텐데요.

간단히 말씀드리자면, 요소를 추가할 때 가득 찬 경우 배열을 늘려준 다음 넣으시면 되겠습니다.

add(E element) {
  if (가득 차 있다면?) {
    // 먼저 두배 크기 배열을 새롭게 만들고,
    // 기존 배열을 복사해 넣은 뒤,
    // 추가한 아이템을 배열에 저장하면 되겠습니다.
  }
}