개발/공부

[오류] error: no suitable method found for toArray(int[])

할루솔이 2023. 6. 23. 00:36
반응형
발생한 오류

error: no suitable method found for toArray(int[])

 

이 오류는 타입이 달라서 생기는 오류이고,

아래 코드에서 ArrayList의 요소를 int배열로 변환하려다 생겼다.

ArrayList<Integer> list = new ArrayList();

int[] arr;

...

arr = list.toArray(new int[list.size()]);

ArrayList는 객체의 리스트이며, toArray() 메서드를 사용하여 배열로 변환할 때, 

기본 데이터 타입인 int 타입 배열로 변환하는 것은 불가능하다.

 

해결 방법

wrapper클래스인 Integer를 사용해서 변환하기!

ArrayList<Integer> list = new ArrayList<>();

int[] arr = new int[list.size()];

for (int i = 0; i < list.size(); i++) {
    arr[i] = list.get(i); 
}

 

반복문을 사용해서 배열 arr에 list요소를 하나씩 넣어주자!!!

 

 

반응형

'개발 > 공부' 카테고리의 다른 글

인텔리제이 프로젝트 생성하기  (0) 2023.08.26
git vs svn  (0) 2023.08.18
친절한 프로그램?  (0) 2023.06.20
List ->배열, 배열 -> List 로 변환하는 법  (0) 2023.06.19
charAt() - 48은 언제 해야할까?  (0) 2023.06.13